hibernate的环境搭建

来源:互联网 发布:哪里有樱井知香的视频 编辑:程序博客网 时间:2024/06/04 18:19

本文以hibernate来操纵mysql数据库,所以在此之前必须确保mysql数据库已经正确安装好。。。


1、导hibernate包的核心jar包。。。

2、导hbm.xml文件

3、导hibernate.cfg.xml文件

以上三个文件为hibernate环境搭建的基础材料...其可以到hibernate的官网去下载.....在这里我为大家准备好了我自己常用的版本http://download.csdn.net/detail/caihongshijie6/6584855

4、编写pojo类(这里以Student类为例)


[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.njupt.pojo;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Student implements Serializable{  
  6.   
  7.     private int id;  
  8.     private String name;  
  9.     private String pwd;  
  10.     private int age;  
  11.     public int getId() {  
  12.         return id;  
  13.     }  
  14.     public void setId(int id) {  
  15.         this.id = id;  
  16.     }  
  17.     public String getName() {  
  18.         return name;  
  19.     }  
  20.     public void setName(String name) {  
  21.         this.name = name;  
  22.     }  
  23.     public String getPwd() {  
  24.         return pwd;  
  25.     }  
  26.     public void setPwd(String pwd) {  
  27.         this.pwd = pwd;  
  28.     }  
  29.     public int getAge() {  
  30.         return age;  
  31.     }  
  32.     public void setAge(int age) {  
  33.         this.age = age;  
  34.     }  
  35.       
  36.       
  37.       
  38. }  


5、HibernateUtil类

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.njupt.util;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7. public class HibernateUtil {  
  8. //  创建SessionFactory  
  9.     private static SessionFactory sessionFactory;  
  10. //  使用静态代码块(只创建一次)来创建sessionFactory  
  11.     static{  
  12. //      读取配置hibernate.cfg.xml  
  13.         try {  
  14.             Configuration configuration =   
  15.                 new Configuration().configure("hibernate.cfg.xml");  
  16.             sessionFactory = configuration.buildSessionFactory();  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21. //  获得session  
  22.     public static Session getSession(){  
  23.         return sessionFactory.openSession();  
  24.     }  
  25. //  关闭session,session总是默认保存数据(save(),get(),load()...)  
  26. //  很可能出现内存泄露  
  27.     public static void close(Session session){  
  28.         if(session!=null){  
  29.             if(session.isOpen()){// null.isOpen  
  30.                 session.close();  
  31.             }  
  32.         }  
  33.     }  
  34.       
  35. }  


6、进行测试

编写测试类SessionTest

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.njupt.util;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5.   
  6. import org.hibernate.Hibernate;  
  7. import org.hibernate.HibernateException;  
  8. import org.hibernate.Query;  
  9. import org.hibernate.Session;  
  10. import org.hibernate.Transaction;  
  11. import org.junit.Test;  
  12.   
  13. import com.njupt.pojo.Student;  
  14. import com.njupt.util.HibernateUtil;  
  15.   
  16. public class SessionTest {  
  17.   
  18.     // public void testSave(){  
  19.     // // System.out.println("保存");  
  20.     // String str =null;  
  21.     // System.out.println(str.length());  
  22.     // }  
  23.     // 1 保存操作  
  24.     @Test  
  25.     public void testSave() {  
  26.         Session session = null;  
  27.         Transaction transaction = null;  
  28.         try {  
  29.             // 首先获得session  
  30.             session = HibernateUtil.getSession();  
  31.             // 获得Transaction  
  32.             transaction = session.getTransaction();  
  33.             // 开启事务  
  34.             transaction.begin();  
  35.             // 创建person对象  
  36.             Student person = new Student();  
  37.   
  38.             person.setName("zzt_love_hjd");  
  39.             person.setAge(21);  
  40.             person.setPwd("123321");  
  41.             // 使用session保存person对象  
  42.             session.save(person);  
  43.             // 提交事务  
  44.             transaction.commit();  
  45.         } catch (Exception e) {  
  46.             // 打印异常信息  
  47.             e.printStackTrace();  
  48.             // 回滚  
  49.             transaction.rollback();  
  50.         } finally {  
  51.             // 关闭session  
  52.             HibernateUtil.close(session);  
  53.         }  
  54.     }  
  55.   
  56.     // 查询id=2的person对象  
  57.     @Test  
  58.     public void testGet1() {  
  59.         Session session = null;  
  60.         // 查询操作,对数据库的表没有任何修改,不用开启事务  
  61.         try {  
  62.             session = HibernateUtil.getSession();  
  63.             // session.get()  
  64.             Student person = (Student) session.get(Student.class3);  
  65.             System.out.println("-------------------------------");  
  66.             System.out.println(person.getId() + "," + person.getName());  
  67.         } catch (Exception e) {  
  68.             // TODO: handle exception  
  69.             e.printStackTrace();  
  70.         } finally {  
  71.             HibernateUtil.close(session);  
  72.         }  
  73.     }  
  74.   
  75.     // 使用load加载对象  
  76.     @Test  
  77.     public void testLoad1() {  
  78.         Session session = null;  
  79.         try {  
  80.             session = HibernateUtil.getSession();  
  81.             // 没有发出sql语句  
  82.             // load():不会立刻去查询数据库,hibernate会返回一个代理对象  
  83.             // 暂时代替person对象(避免对数据库过于频繁的访问,  
  84.             // 提高系统性能)  
  85.             // hibernate 返回代理对象是cglib动态代理  
  86.             // cglib返回是目标对象(Person)的子类对象  
  87.             Student person = (Student) session.load(Student.class1);  
  88.             System.out.println("-------------------");  
  89.             // 真正需要访问数据的时候  
  90.             // 发出了sql语句,person发出的sql语句  
  91.             // hibernate返回的代理对象发出对应sql语句  
  92.             System.out.println(person.getName());  
  93.         } catch (Exception e) {  
  94.             // TODO: handle exception  
  95.             e.printStackTrace();  
  96.         } finally {  
  97.             HibernateUtil.close(session);  
  98.         }  
  99.     }  
  100.   
  101.     // get()查询的数据,在数据库中不存在  
  102.     // 返回null  
  103.     @Test  
  104.     public void testGet2() {  
  105.         Session session = null;  
  106.         try {  
  107.             session = HibernateUtil.getSession();  
  108.             Student person = (Student) session.get(Student.class2);  
  109.             System.out.println(person);  
  110.         } catch (Exception e) {  
  111.             // TODO: handle exception  
  112.             e.printStackTrace();  
  113.         } finally {  
  114.             HibernateUtil.close(session);  
  115.         }  
  116.     }  
  117.   
  118.     // load()查询数据库中没有的数据  
  119.     // 如果数据库中没有与之对应的数据,则抛出  
  120.     // ObjectNotFoundException  
  121.     // 常见异常:SQLException / HibernateException / NestableRuntimeException  
  122.     @Test  
  123.     public void testLoad2() {  
  124.         Session session = null;  
  125.         try {  
  126.             session = HibernateUtil.getSession();  
  127.             Student person = (Student) session.load(Student.class2);  
  128.             System.out.println(person);  
  129.         } catch (Exception e) {  
  130.             // TODO: handle exception  
  131.             e.printStackTrace();  
  132.         } finally {  
  133.             HibernateUtil.close(session);  
  134.         }  
  135.     }  
  136.   
  137.     // load:需要的时候才发出sql语句,去数据库中真实的查询  
  138.     // 这叫做延迟加载/懒加载(预习)  
  139.     // proxy:代理  
  140.     // org.hibernate.LazyInitializationException:  
  141.     // could not initialize proxy - no Session  
  142.     // hibernate.load()返回的代理对象的生命周期跟session保持一致  
  143.     // 关闭session,代理对象也不能使用了,不能发出sql语句  
  144.     @Test  
  145.     public void testLoad3() {  
  146.         Session session = null;  
  147.         Student person = null;  
  148.         try {  
  149.             session = HibernateUtil.getSession();  
  150.             person = (Student) session.load(Student.class1);  
  151.         } catch (Exception e) {  
  152.             e.printStackTrace();  
  153.         } finally {  
  154.             HibernateUtil.close(session);  
  155.         }  
  156.   
  157.         System.out.println(person.getName());  
  158.   
  159.     }  
  160.   
  161.     // 修改操作  
  162.     @Test  
  163.     public void testUpdate() {  
  164.         Session session = null;  
  165.         try {  
  166.             session = HibernateUtil.getSession();  
  167.             session.beginTransaction();// 直接开启一个事务  
  168.             Student person = (Student) session.get(Student.class1);  
  169.             person.setName("cangsong");  
  170.             person.setAge(30);  
  171.             session.update(person);  
  172.   
  173.             // getTransaction().commit();获得开启的事务,并提交  
  174.             session.getTransaction().commit();  
  175.         } catch (Exception e) {  
  176.             // TODO: handle exception  
  177.             e.printStackTrace();  
  178.             // session.getTransaction().rollback();获得开启的事务,并回滚  
  179.             session.getTransaction().rollback();  
  180.         } finally {  
  181.             HibernateUtil.close(session);  
  182.         }  
  183.     }  
  184.   
  185.     // 删除操作  
  186.     @Test  
  187.     public void testDelete() {  
  188.         Session session = null;  
  189.         try {  
  190.             session = HibernateUtil.getSession();  
  191.             session.beginTransaction();  
  192.             Student person = (Student) session.get(Student.class2);  
  193.             session.delete(person);  
  194.             session.getTransaction().commit();  
  195.         } catch (Exception e) {  
  196.             // TODO: handle exception  
  197.             e.printStackTrace();  
  198.             session.getTransaction().rollback();  
  199.         } finally {  
  200.             HibernateUtil.close(session);  
  201.         }  
  202.     }  
  203.   
  204.     // 查询t_person中所有的对象  
  205.     @Test  
  206.     public void testQuery3() {  
  207.         Session session = null;  
  208.         try {  
  209.             session = HibernateUtil.getSession();  
  210.             // createQuery("hql语句"):用session来创建一个Query对象  
  211.             // 封装hql语句  
  212.             Query query = session.createQuery("from Person");  
  213.             // 使用query做查询操作,返回的结果保存到了一个list集合当中  
  214.             List list = query.list();  
  215.             // 对集合的遍历  
  216.             Iterator<Student> iterator = list.iterator();  
  217.             while (iterator.hasNext()) {  
  218.                 Student person = iterator.next();  
  219.                 System.out.println(person.getId() + "," + person.getName());  
  220.             }  
  221.         } catch (Exception e) {  
  222.             // TODO: handle exception  
  223.             e.printStackTrace();  
  224.         } finally {  
  225.             HibernateUtil.close(session);  
  226.         }  
  227.     }  
  228.   
  229. }  


经过以上的6步这时候,你便能在通过hibernate来操作数据库了................................

!!!!特别提醒:要想使用hibernate的自动建表功能,可以在hibernate.cfg.xml中按如下配置:

<property name="hbm2ddl.auto">update</property> 

0 0