第一次作业 搭建Hibernate环境 实现第一个Hibernate demo

       首先我的电脑莫名其妙就不好使了,刚一开机就是连不上网,没有无线服务,我很是头疼,马上就要写作业了,

弄出这样头疼的事,真的很难受,接下来就是各种百度吧,最后用了将近一个小时时间解决了,电脑出现问题真的

是很难受。好了,现在一切顺利, 言归正转。


       今天的主要内容就是搭建Hibernate环境,并实现第一个关于Hibernate框架的demo。

首先我先下载了老师给分享的网盘的软件以及Hibernate的jar包到桌面上,但是我的电脑在安装mysql的时候说

    提示这个问题。

所以我需要重新下载一个mysql 8.0.11的最新版。

使用这个框架第一步就是导jar包,

Hibernate是一个持久化框架

Hibernate核心jar包  Hibernate3.jar

Hibernate必须的jar包   Hibernate/lib/required目录下

Hibernate的jpa实现  Hibernate/lib/jpa目录

日志    log4j


介绍log4j简单使用

在程序中使用log4j记录日志

步骤一:定义记录器

步骤二:使用log4j提供每个级别方法 记录日志

LOG.fatal("致命错误");

LOG.error("普通错误");

LOG.warn("警告信息");

LOG.info("普通信息");

LOG.debug("调试信息");

LOG.trace("堆栈信息");

常用 :error、warn、info、debug


3.编写数据库 表与实体类

create database h1;

createtablecustomer(

id int primary key auto_increment,

name varchar(20),

age int,

city varchar(20)

);


现在类和表都有了  

4.创建一个类与表的映射文件

    1).名称

        类名.hbm.xml------Customer.hbm.xml

    2).位置

         与实体类在同一个包下

     3).约束

              hibernate3.jar  org/hibernate/hibernate-mapping-3.0.dtd文件中定义

                 <!DOCTYPE hibernate-configuration PUBLIC
                 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

                  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

    4)元素

          <class name ="cn.itcast.domain .Customer" table="customer">
<id name="id" colum="id">
   <generate class="native"></generate>  <!--是一个主键生成策略-->
</id>

</class>

其中name代表实体类名  table代表表名

column=id代表的是table表中的字段

其他属性使用proper标签来映射

<hibernate-mapping>

<class name ="cn.itcast.domain .Customer" table="customer">
<id name="id" column="id">
   <generate class="native"/><!-- 主键生成策略 -->
 </id>
<property name ="age" column="age" type="int"/><!-- 基于java写法 -->
<property name="name"   column="name" type="string"/> <!-- 基于hibernate写法 -->
<property name="city" >
<column name="city" sql-type="varchar(20)"></column>

</property><!-- 基于mysql写法 -->

</class>

</hibernate-mapping>



5.创建一个Hibernate的配置文件

   Hibernate.cfg.xml放置在src下  (名字不能瞎写)

位置:src下

名称:hibernate.cfg.xml

约束:hibernate3.jar  org/hibernate/hibernate-mapping-3.0.dtd

          <!DOCTYPE hibernate-configuration PUBLIC
                 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

                  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

元素:

关于元素



6. 编写代码,执行crud操作

模板:

1)得到配置对象

     Configuration config=new Configuartion(),config();

2)得到一个sessionFactory

     SessionFactory Factory=config.buildSessionFactory();

3)得到一个Session

       Session session=Factory.openSession();

4)开启服务

    Session.beginTransaction();

5)执行操作--具体的crud操作

6)提交操作 

      t.commit();

7)释放资源

        session.close();

        factory.close();


操作:添加

测试类