hibernate入门

hibernate官网:http://www.hibernate.org/

1、对象-关系映射文件(*.hbm.xml)

  Hibernate 采用 XML 格式的文件来指定对象和关系数据之间的映射. 在运行时 Hibernate 将根据这个映射文件来生成各种 SQL 语句

  映射文件的扩展名为 .hbm.xml 这里Customer.hbm.xml文件
  
   dtd规范:hibernate3.jar/org.hibernate/hibernate-mapping-3.0.dtd
1 <!DOCTYPE hibernate-mapping PUBLIC 
2     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

 

样例代码:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC 
 3     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5     
 6 <hibernate-mapping>
 7   <!-- 
 8       class:建立javaBean和表之间的关系
 9         * name:对应的javabean的完整的类路径
10         * table:表名
11    -->
12   <class name="cn.zengfansheng.primer.Customer" table="customers">
13     
14     <!-- 
15       id:用于映射表的主键
16      -->
17     <id name="id" type="integer">
18        <column name="id"></column>
19        <!-- 配置主键生成策略,获取表中的最大值+1 ? -->
20        <generator class="increment"/>
21     </id> 
22     <!-- 
23        property:待映射的持久化类中的属性
24          * name:持久化类中的属性名
25          * type":property name="name"  name属性: Customer类中是String
26                  column name="name"    name字段名,customers表中是varchar 
27            type:指定的是hibernate中的数据类型,该数据类型是java类型和数据库中类型的桥梁  
28                 ="string"   表示java的属性的类型是String  数据中类型是varhcar类型   
29                 ="integer"  表 示java的属性的类型是Integer  数据中类型是int类型
30                 string对应的是org.hibernate.type.StringType类
31                 integer对应的是org.hibernate.type.IntegerType类
32                 
33       column: 持久化类中的属性对应的表中的字段
34          * name:表示表中的字段名
35      --> 
36     <property name="name" type="string">
37       <column name="name"></column>
38     </property>  
39     
40     <property name="age" type="integer">
41       <column name="age"></column>
42     </property>  
43     
44      <property name="des" type="text">
45       <column name="des"></column>
46     </property>  
47     
48   </class>
49   
50 </hibernate-mapping>  
2、 hibernate.cfg.xml
  创建 Hibernate 配置文件, Hibernate 从其配置文件中读取和数据库连接的有关信息, 这个文件应该位于应用的 classpath下.位于src目录下
   注:该映射文件的规范在org.hibernate.hibernate-configuration-3.0.dtd文件中
1 <!DOCTYPE hibernate-configuration PUBLIC
2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
3     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

   配置参考:

hibernatezip\hibernate-distribution-3.5.6-Final-dist\hibernate-distribution-3.5.6-Final\documentation\manual\zh-CN\hibernate_reference.pdf-3.3 JDBC 连接

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">    
 5 <hibernate-configuration>
 6    <session-factory>
 7      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>指定连接数据库的基本属性信息
 8      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
 9      <property name="hibernate.connection.username">root</property>
10      <property name="hibernate.connection.password">root</property>
11      
12      <!-- 配置数据库的方言,通过方言,让计算机知道连接的是哪种数据库 -->
13      <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
14      <!--在控制台上输出sql语句 -->
15      <property name="hibernate.show_sql">true</property>
16      <!--格式化sqlk语句 -->
17      <property name="hibernate.format_sql">true</property>
18      <property name="hibernate.hbm2ddl.auto">create</property><!-- 指定程序运行时是否在数据库自动生成数据表 -->
19      <!-- 
20          * none:
21             * 如果表存在,不会创建表,直接插入数据到表中
22             * 如果表不存在,不会创建表,此时不能插入数据到表中
23          *  create:
24             *  如果表存在,先删除表,在创建表,插入数据到表中
25             *  如果表不存在,先创建表,再插入数据到表中
26             
27          *  update:
28             *  如果表存在,
29                  * 如果由javaBean生成的表和数据库中表的结构没有变化,插入数据到表中
30                  * 如果由javaBean生成的表和数据库中表的结构有变化,更新数据库中表的结构,插入数据到表中
31             *  如果表不存在,先创建表,在插入数据到表中
32       -->
33      <property name="hibernate.hbm2ddl.auto">update</property>
34      <mapping resource="cn/zengfansheng/primer/Customer.hbm.xml" />指定程序运行需要关联的映射文件
35    </session-factory>
36 </hibernate-configuration>

 3、javahibernatesql类型对应关系

   
 4、Configuration 类
   a)Configuration 类负责管理 Hibernate 的配置信息。
   包括如下内容:
•Hibernate运行的底层信息:数据库的URL、用户名、密码、JDBC驱动类,数据库Dialect,数据库连接池等(对应 hibernate.cfg.xml 文件)。
•持久化类与数据表的映射关系(*.hbm.xml 文件)
   
   b)创建 Configuration 的两种方式
•属性文件(hibernate.properties):

    Configuration cfg = new Configuration();

•Xml文件(hibernate.cfg.xml)

    Configuration cfg = new Configuration().configure();

底层代码说明:hibernate.cfg.xml该文件名不能变

1 public Configuration configure() throws HibernateException {
2         configure( "/hibernate.cfg.xml" );
3         return this;
4     }
 5、SessionFactory接口
    a)Configuration对象根据当前的配置信息生成 SessionFactory 对象。SessionFactory 对象一旦构造完毕,
     即被赋予特定的配置信息(SessionFactory 对象中保存了当前的数据库配置信息和所有映射关系以及预定义的SQL语句。
    同时,SessionFactory还负责维护Hibernate的二级缓存)。
1 Configuration cfg = new Configuration().configure();
2 SessionFactory sf = cfg.buildSessionFactory();

   b)是线程安全的。 

   c)SessionFactory是生成Session的工厂

1 Session session = sf.openSession();

  d)构造 SessionFactory很消耗资源,一般情况下一个应用中只初始化一个 SessionFactory对象。

6、session接口 

   a) Session 是应用程序与数据库之间交互操作的一个单线程对象,是 Hibernate 运作的中心,所有持久化对象必须在 session 的管理下才可以进行持久化操作。

    此对象的生命周期很短。Session 对象有一个一级缓存,显式执行 flush 之前,所有的持久层操作的数据都缓存在 session 对象处。相当于 JDBC 中的 Connection。

   b) 持久化类与 Session 关联起来后就具有了持久化的能力。

   c) 是线程不安全的
   d) Session 类的方法:
•取得持久化对象的方法: get() load()
•持久化对象都得保存,更新和删除:save(),update(),saveOrUpdate(),delete()
•开启事务: beginTransaction().
•管理 Session 的方法:isOpen(),flush(), clear(), evict(), close()等
 
7、Transaction接口
  a) 代表一次原子操作,它具有数据库事务的概念。所有持久层都应该在事务管理下进行,即使是只读操作。
 1 Transaction tx = session.beginTransaction();
    b) 常用方法:
•commit():提交相关联的session实例
•rollback():撤销事务操作
•wasCommitted():检查事务是否提交
  
8、 Hibernate运行过程
  

1、应用程序先调用Configuration,该类读取Hibernate配置文件及映射文件中的信息,

2、并用这些信息生成一个SessionFactory对象,

3、然后从SessionFactory对象生成一个Session对象,

4、并用Session对象生成Transaction对象;

    A、可通过Session对象的get(),load(),save(),update(),delete()saveOrUpdate()等方法对PO进行加载、保存、更新、删除、等操作;

    B、在查询的情况下,可通过Session对象生成一个Query对象,然后利用Query对象执行查询操作;如果没有异常,Transaction对象将提交这些操作到数据库中。

 
 
 
总结: 

* 搭建hibernate项目:
  * 创建java的应用工程

  * 引入jar包
    * hibernate的相关jar包
      hibernate-distribution-3.5.6-Final\lib\required\*.jar
      hibernate-distribution-3.5.6-Final\hibernate3.jar

      hibernate-annotations-3.4.0.GA\lib\test\slf4j-log4j12.jar
      hibernate-annotations-3.4.0.GA\lib\test\log4j.jar

  * junit测试的jar包
      junit-4.8.2.jar

   * mysql的驱动jar包
      mysql-connector-java-5.1.10-bin.jar

  * 创建表
    CREATE TABLE customers
    (
      id INT PRIMARY KEY,
      NAME VARCHAR(12),
      age INT,
      des TEXT
    )

  * 创建表对应的javaBean
    public class Customer {
      //OID:Object id,表示hibernate中持久化类的唯一标识
      private Integer id;
      private String name;
      private Integer age;
      private String des;
    }

  * 创建表和javaBean之间额映射关系
    * 创建Customer.hbm.xml文件,该文件的规范放置到hibernate3.jar/org.hibernate.mapping-3.0.dtd
    * 配置见例子


  * 创建hibernate.,cfg.xml文件,
      * 放置到src下, 该文件的规范放置到hibernate3.jar/org.hibernate.configuration-3.0.dtd
    * 配置见例子

  * 创建App类测试

 1 import org.hibernate.Session;
 2 import org.hibernate.SessionFactory;
 3 import org.hibernate.Transaction;
 4 import org.hibernate.cfg.Configuration;
 5 
 6 public class App {
 7 
 8     public static void main(String[] args) {
 9     
10         /*
11          * 加载hibernate.cfg.xml映射文件
12          *   * config:保存了连接数据库的信息和映射文件的配置信息
13          */
14         Configuration config = new Configuration();
15         // 默认加载类路径下的hibernate.cfg.xml
16         config.configure();
17         
18          /*
19           * 获取sessionFactory
20           * * 利用config保存的信息创建SessionFactory,
21           * * SessionFactory 保存了连接数据库的信息和映射文件的配置信息,预定义的sql语句
22           *   SessionFactory是线程安全的,最好有一个sessionFactory
23           */
24         
25         SessionFactory sf = config.buildSessionFactory();
26         //获取session
27         Session session  =sf.openSession();
28         //开始事务
29         Transaction transaction = session.beginTransaction();
30         //实例Customer对象
31         Customer c = new Customer();
32         c.setName("hacket");
33         c.setAge(32);
34         c.setDes("消费");
35         
36         session.save(c);
37         
38         transaction.commit();
39         
40         session.close();
41         
42     }
43 }
 改版后:
  1 import java.util.List;
  2 
  3 import org.hibernate.Query;
  4 import org.hibernate.Session;
  5 import org.hibernate.SessionFactory;
  6 import org.hibernate.Transaction;
  7 import org.hibernate.cfg.Configuration;
  8 import org.junit.Test;
  9 
 10 public class App {
 11     
 12     static SessionFactory sf=null;
 13     static{
 14         /*
 15          * 加载hibernate.cfg.xml映射文件
 16          *   * config:保存了连接数据库的信息和映射文件的配置信息
 17          */
 18         Configuration config=new Configuration();
 19         
 20         /*
 21          * config.configure();
 22          *    * 默认加载类路径下的hibernate.cfg.xml
 23          * config.configure("cn/zengfansheng/primer/hibernate.cfg.xml");
 24          *    * 加载指定路径下的hibernate.cfg.xml文件
 25          */
 26         config.configure("cn/zengfansheng/primer/hibernate.cfg.xml");
 27         
 28         /*
 29          * 方法一:通过代码的方式加载映射文件
 30          *   config.addResource("cn/zengfansheng/primer/Customer.hbm.xml");
 31          * 方法二:
 32          *    * config.addClass(Customer.class);
 33          *    * 要求:Customer.hbm.xml配置文件的名称必须和Customer.class的类名一致,同时两个文件要放置到同一个目录下
 34          */
 35         //方法一
 36         //config.addResource("cn/zengfansheng/primer/Customer.hbm.xml");
 37         
 38         //方法二
 39         config.addClass(Customer.class);
 40          /*
 41           * 获取sessionFactory
 42           * * 利用config保存的信息创建SessionFactory,
 43           * * SessionFactory 保存了连接数据库的信息和映射文件的配置信息,预定义的sql语句
 44           *   SessionFactory是线程安全的,最好有一个sessionFactory
 45           */
 46          sf=config.buildSessionFactory();
 47     }
 48     
 49     @Test
 50     public  void saveCustomer() {
 51         //获取session
 52         Session s=sf.openSession();
 53         //开始事务
 54         Transaction tx=s.beginTransaction();
 55         //实例Customer对象
 56         Customer c=new Customer();
 57         c.setName("银晶");
 58         c.setAge(54);
 59         c.setDes("需");
 60         //保存
 61         s.save(c);
 62         //提交
 63         tx.commit();
 64         //关闭session
 65         s.close();
 66     }
 67     
 68     @Test
 69     public  void updateCustomer() {
 70         Session s=sf.openSession();
 71         Transaction tx=s.beginTransaction();
 72 
 73         Customer c=new Customer();
 74         c.setId(1);
 75         c.setName("铁晶");
 76         c.setAge(53);
 77         c.setDes("酷");
 78         s.update(c);
 79         
 80         tx.commit();
 81         s.close();
 82     }
 83     
 84     @Test
 85     public  void findCustomerById() {
 86         Session s=sf.openSession();
 87         Transaction tx=s.beginTransaction();
 88         
 89         Integer id=1;
 90         Customer c=(Customer)s.get(Customer.class, id);
 91         System.out.println(c.getId()+"   "+c.getName());
 92         
 93         tx.commit();
 94         s.close();
 95     }
 96 
 97 
 98     @Test
 99     public  void deleteCustomerById() {
100         Session s=sf.openSession();
101         Transaction tx=s.beginTransaction();
102         
103         Integer id=1;
104         Customer c=(Customer)s.get(Customer.class, id);
105         
106         s.delete(c);
107         
108         tx.commit();
109         s.close();
110     }
111     
112     
113     @Test
114     public  void findCustomers() {
115         Session s=sf.openSession();
116         Transaction tx=s.beginTransaction();
117         
118         /*
119          * hql:面向对象的语句
120          * Query:接口:执行对数据库的crud操作
121          */
122         Query query=s.createQuery("from Customer c");
123         List<Customer> list=query.list();
124         for(Customer c:list){
125             System.out.println(c.getId()  +"   "+c.getName());
126         }
127         
128         tx.commit();
129         s.close();
130     }    
131 }
 
by hacket
原文地址:https://www.cnblogs.com/hacket/p/3086989.html