首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Hibernate复习(1)-最基础的示例

2012-09-11 
Hibernate温习(1)--最基础的示例有关Spring的知识大部分都已经温习完毕,今天开始转向Hibernate的温习工作

Hibernate温习(1)--最基础的示例
有关Spring的知识大部分都已经温习完毕,今天开始转向Hibernate的温习工作了
必须包hibernate-distribution-3.5.3-Final\hibernate3.jar
         hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
         hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
         hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
         hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
         hibernate-distribution-3.5.3-Final\lib\required\slf4j-api-1.5.8.jar
首先在hibernate资源包中找到:hibernate-distribution-3.5.3-Final\project\tutorials\web\src\main\resources\hibernate.cfg.xml,将这个配置文件复制到你的项目SRC目录下,然后根据实际情况进行适当修改,我的示例中修改后为

Xml代码 

<span style="font-size: large;"><span style="font-size: large;"><?xml version="1.0" encoding="utf-8" ?>  <!DOCTYPE hibernate-configuration PUBLIC      "-//Hibernate/Hibernate Configuration DTD 3.0//EN"      "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  <hibernate-configuration>      <session-factory>        <!--数据库连接设置-->          <property name="connection.driver_class">com.mysql.jdbc.Driver</property>          <property name="connection.url">jdbc:mysql:///test</property>          <property name="connection.username">root</property>          <property name="connection.password">root</property>            <!--JDBC连接池大小-->          <property name="connection.pool_size">2</property>          <!-- 数据库语言 -->          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>          <!-- Hibernate当前的会话上下文 -->          <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>          <!-- 禁用二级缓存 -->          <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>          <!-- 控制台显示SQL语句 -->          <property name="show_sql">true</property>         <!-- 格式化SQL语句 -->          <property name="hibernate.format_sql">true</property>        <!--          启动时删数据库中的表,然后创建,退出时不删除数据表           <property name="hbm2ddl.auto">create</property>      -->      <!--          启动时删数据库中的表,然后创建,退出时自动删除所有表           <property name="hbm2ddl.auto">create-drop</property>      -->      <!--          自动修改,如果表结构与实体类不一致,那么就更新表结构,数据会保留          (如果原表不存在,就创建新表;如果缺少相应的字段,就加入;对于原来存在的多余字段,不作处理)          <property name="hbm2ddl.auto">update</property>      -->      <!--          自动校验,如果表结构与实体类不一致,那么不做任何操作,报错           <property name="hbm2ddl.auto">validate</property>      -->           <!-- Drop and re-create the database schema on startup -->          <property name="hbm2ddl.auto">create</property>            <!-- 实体关系映射文件 -->          <mapping resource="com/javacrazyer/domain/Student.hbm.xml"/>      </session-factory>  </hibernate-configuration></span></span>  


数据库方言一定要设定对,跟数据库驱动匹配org.hibernate.dialect.MySQLDialect
否则的话就会出现下面这个错误

Java代码 
<span style="font-size: large;"><span style="font-size: large;">Unknown table 'system_sequences' in information_schema</span></span> 


其次,看看实体类Student.java

Java代码 
<span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.domain;    import java.util.Date;    /**  * 学生实体类 --> 按JavaBean的形式定义  *   */  public class Student {      private int id;  //OID 对象标识符      private String name;      private int age;      private boolean gender;      private Date birthday;      private double score;            public int getId() {          return id;      }      public void setId(int id) {          this.id = id;      }      public String getName() {          return name;      }      public void setName(String name) {          this.name = name;      }      public int getAge() {          return age;      }      public void setAge(int age) {          this.age = age;      }      public boolean isGender() {          return gender;      }      public void setGender(boolean gender) {          this.gender = gender;      }      public Date getBirthday() {          return birthday;      }      public void setBirthday(Date birthday) {          this.birthday = birthday;      }      public double getScore() {          return score;      }      public void setScore(double score) {          this.score = score;      }            @Override      public String toString(){          return "id=" + id + ",name=" + name + ",gender=" + gender + ",age=" + age          + ",birthday=" + this.birthday + ",score=" + score;      }        }</span></span>  


实体关系映射文件Student.hbm.xml,具体内容也可以参照hibernate资源包下:
hibernate-distribution-3.5.3Final\project\tutorials\web\src\main\resources\org\hibernate\tutorial\
domain\Person.hbm.xml
那么进行修改后的内容为

Xml代码 
<span style="font-size: large;"><span style="font-size: large;"><?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >  <hibernate-mapping>      <class name="com.javacrazyer.domain.Student" table="student">          <id name="id" column="id">              <generator column="name"/>          <property name="age"/>          <property name="gender"/>          <property name="birthday"/>          <property name="score"/>      </class>  </hibernate-mapping></span></span>  


现在介绍下hbm.xml映射文件中各种属性的介绍吧
1.class 节点
name: 类名
table: 类对应表名,默认为类名称
dynamic-update: 生成更新字段时,只包含发生变动的字段,默认为false。
dynamic-insert: 生成insert语句时仅包含非null字段
Proxy: 代理类,默认为空
discriminator-value: 子类辨别标识用于多态支持
where: 通过限定条件查询结果集。如:查询有籍在校学生的信息可以使用"where studentstatus='0'"
2.id节点
1.column                字段名称
2.type                  字段类型
3.length                字段长度
4.unsaved-value         用于判断对象值是否已经保存
5.generator-class       主键产生方式
                        assigned
                        hilo
                        seqhilo
                        increment
                        identity
                        sequence
                        native
                        uuid.hex
                        uuid.string
                        foreign

---------------------------------------------------------------------------
主键产生方式说明
increment(递增)
用于为long, short或者int类型生成唯一标识。只有在没有其他进程往同一张表中插入数据时才能使用。 在集群下不要使用。
identity
对DB2,MySQL, MS SQL Server, Sybase和HypersonicSQL的内置标识字段提供支持。返回的标识符是long, short 或者int类型的。
sequence (序列)
在DB2,PostgreSQL, Oracle, SAP DB, McKoi中使用序列(sequence),而在Interbase中使用生成器(generator)。返回的标识符是long, short或者 int类型的。
hilo (高低位)
使用一个高/低位算法来高效的生成long, short或者 int类型的标识符。给定一个表和字段(默认分别是是hibernate_unique_key 和next_hi)作为高位值得来源。高/低位算法生成的标识符只在一个特定的数据库中是唯一的。在使用JTA获得的连接或者用户自行提供的连接中,不要 使用这种生成器。
seqhilo(使用序列的高低位)
使用一个高/低位算法来高效的生成long, short或者 int类型的标识符,给定一个数据库序列(sequence)的名字。
uuid.hex
用一个128-bit的UUID算法生成字符串类型的标识符。在一个网络中唯一(使用了IP地址)。UUID被编码为一个32位16进制数字的字符串。
uuid.string
使用同样的UUID算法。UUID被编码为一个16个字符长的任意ASCII字符组成的字符串。不能使用在PostgreSQL数据库中
native(本地)
根据底层数据库的能力选择identity, sequence 或者hilo中的一个。
assigned(程序设置)
让应用程序在save()之前为对象分配一个标示符。
foreign(外部引用)
-------------------------------------------------
3.property 节点
1.column                数据库表字段名称
2.type                  类型
3.length                长度
4.not-null              字段是否允许为空
5.unique                字段是否允许唯一(是否允许重复值)
6.insert                insert操作时,是否允许包含本字段数值
7.update                update操作时,是否包含本字段数据


特别说明
现在有个问题,按平常思路就是,得在数据库中创建一个student表吧,字段及类型得与Student类吻合,其实不用,为什么这么说,因为在hibernate.cfg.xml中 <property name="hibernate.hbm2ddl.auto">update</property>这句话配置的值为update就表示没有表的情况下会在执行数据库操作前自动创建数据库表,这下就省了好多事了


不过,如果你非要手工去创建,写SQL语句在数据库工具中也没必要,hibernate有相应的API支持你生成对应的数据库表
下面这个类就就可以
创建数据库表的类DBScriptExport .Java


Java代码 
<span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.common;    import org.hibernate.cfg.Configuration;  import org.hibernate.tool.hbm2ddl.SchemaExport;    /**  * 根据对象关系映射文件直接生成数据库表或生成建表的脚本  *   */  public class DBScriptExport {        public static void main(String[] args) {          export2File("dbcript.sql");      }            public static void export2DB(){          //加载Hibernate的全局配置文件          Configuration config = new Configuration().configure();          SchemaExport export = new SchemaExport(config);          export.create(true, true);      }            public static void export2File(String dest){          Configuration config = new Configuration().configure();          SchemaExport export = new SchemaExport(config);                    export.setOutputFile(dest)              .setDelimiter(";")              .setFormat(true)              .create(true, false);      }    }  </span></span>  


获取session的HibernateUtil.java

Java代码 
<span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.common;    import org.hibernate.Session;  import org.hibernate.SessionFactory;  import org.hibernate.cfg.Configuration;    /**  * Hibernate工具类  *   */  public class HibernateUtil {      private static final SessionFactory factory;            private HibernateUtil(){}            static{          //加载Hibernate全局配置文件,根据配置信息创建SessionFactory工厂实例          factory = new Configuration().configure().buildSessionFactory();      }            public static SessionFactory getSessionFactory(){          return factory;      }            public static Session getSession(){          return factory.openSession();      }  }  </span></span> 

最后的测试类HibernateTest.java

Java代码 
<span style="font-size: large;"><span style="font-size: large;">package com.javacrazyer.test;    import java.util.Date;  import java.util.List;    import org.hibernate.Criteria;  import org.hibernate.HibernateException;  import org.hibernate.Query;  import org.hibernate.Session;  import org.hibernate.Transaction;  import org.hibernate.criterion.Order;  import org.junit.Assert;  import org.junit.Test;    import com.javacrazyer.common.HibernateUtil;  import com.javacrazyer.domain.Student;    /**  * 使用Hibernate API完成CRUD  * 更复杂的持久化操作需要使用到Query接口  *   */  public class HibernateTest {            @Test      public void testAdd(){          Student stu = new Student();          stu.setName("test");          stu.setBirthday(new Date());          stu.setAge(1);          stu.setGender(true);          stu.setScore(66.8);                    //利用工厂打开一个Session实例          Session session = HibernateUtil.getSession();                    //开启一个操作事务          Transaction tx = session.beginTransaction();                    //利用session进行持久化操作          session.save(stu);                    //提交事务          tx.commit();                    //关闭Session          session.close();      }            @Test      public void getStu(){                    //持久化管理器          Session session = null;          Transaction tx = null;          try{              session = HibernateUtil.getSession();                        tx = session.beginTransaction();                        //根据ID查询实体对象              Student stu = (Student)session.get(Student.class, 1);                            Assert.assertNotNull(stu);              System.out.println(stu);                        tx.commit();          }catch(HibernateException he){              he.printStackTrace();              tx.rollback();          }finally{              if(null != session && session.isOpen()){                  try{                      session.close();                  }catch(HibernateException e){                      e.printStackTrace();                  }              }          }      }            @Test      public void testUpdate(){          Session session = null;                    try{              session = HibernateUtil.getSession();                            session.beginTransaction();                            Student stu = (Student)session.get(Student.class, 1);              stu.setName("zs");              stu.setScore(52.1);                        session.update(stu);                            session.getTransaction().commit();          }catch(HibernateException e){              Assert.fail();              e.printStackTrace();              session.getTransaction().rollback();          }finally{              if(session != null && session.isOpen()){                  session.close();              }          }      }            @Test      public void testDelete(){          Session session = null;                    try{              session = HibernateUtil.getSession();              //session.beginTransaction();                            Student stu = (Student)session.get(Student.class, 2);              System.out.println(stu);              session.delete(stu);                            //session.getTransaction().commit();          }catch(HibernateException e){              Assert.fail();              e.printStackTrace();              //session.getTransaction().rollback();          }finally{              if(session != null && session.isOpen()){                  session.close();              }          }      }            @Test      public void testGet(){          Session session = null;                    try{              session = HibernateUtil.getSession();              session.beginTransaction();                            Student stu = (Student)session.get(Student.class, 2);                System.out.println(stu);                            Student stu2 = (Student) session.get(Student.class, 2);                            System.out.println(stu2);                            session.getTransaction().commit();          }catch(HibernateException e){              Assert.fail();              e.printStackTrace();              session.getTransaction().rollback();          }finally{              if(session != null && session.isOpen()){                  session.close();              }          }      }            @Test      public void testGet2(){              Session session = null;                        session = HibernateUtil.getSession();              session.beginTransaction();              Student stu = (Student)session.get(Student.class, 2);              System.out.println(stu);              session.getTransaction().commit();              session.close();                            session = HibernateUtil.getSession();              session.beginTransaction();              Student stu2 = (Student) session.get(Student.class, 2);              System.out.println(stu2);              session.getTransaction().commit();              session.close();      }            @SuppressWarnings("unchecked")      @Test      public void testQuery(){          Session session = null;          try{              session = HibernateUtil.getSession();              session.beginTransaction();                            Query query = session.createQuery("from Student");              List<Student> stus = query.list();                            for(Student stu : stus){                  System.out.println(stu);              }                            session.getTransaction().commit();                    }catch(HibernateException e){              e.printStackTrace();              session.getTransaction().rollback();          }finally{              if(session != null && session.isOpen()){                  session.close();              }          }      }            @SuppressWarnings("unchecked")      @Test      public void testCriteria(){          Session session = null;          try{              session = HibernateUtil.getSession();              session.beginTransaction();                            Criteria criteria = session.createCriteria(Student.class);                            List<Student> stus = criteria.addOrder(Order.desc("id")).list();                            for(Student stu : stus){                  System.out.println(stu);              }                            session.getTransaction().commit();                    }catch(HibernateException e){              e.printStackTrace();              session.getTransaction().rollback();          }finally{              if(session != null && session.isOpen()){                  session.close();              }          }      }        }</span></span> 


补充说明:
如果在hibernate.cfg.xml中配置的是
<property name="hibernate.hbm2ddl.auto">create</property>
这种配置前提是表已经存在
在这种情况下,只要你在项目的src下新建一个文件夹命名为import.sql,并且里面写上数据库插入语句,那么就会执行插入操作,为什么只是插入,这得跟create值的这种创建啊方式有关,它是启动hibernate时先删除已存在的表,后新建表,新建的表本身就是空的,当然只能进行插入操作了
import.sql
Java代码 
<span style="font-size: large;">insert into student(name,age,gender,birthday,score) values('test2',10,false,now(),11.2);</span>  

这时,如果你在执行上面那个测试类的添加方法,就会发现,结果插入了两条数据,一条是import.sql中的,一条是测试方法中的,显然import.sql中的先执行,因为在hibernate启动时就执行了

热点排行