Hibernate CRUD操作
生活随笔
收集整理的這篇文章主要介紹了
Hibernate CRUD操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
版權聲明:本文為博主原創文章,如需轉載請標注轉載地址
博客地址:http://www.cnblogs.com/caoyc/p/5594789.html?
對于Hibernate的增刪改查,我們還是用一個案例來說明
下面是整個項目的目錄結構:
?
一、com.mypro.domain包
1、封裝person域模型
1 package com.mypro.domain; 2 3 public class Person { 4 5 private int id; 6 private String name; 7 private int age; 8 private String gender; 9 public int getId() { 10 return id; 11 } 12 public void setId(int id) { 13 this.id = id; 14 } 15 public String getName() { 16 return name; 17 } 18 public void setName(String name) { 19 this.name = name; 20 } 21 public int getAge() { 22 return age; 23 } 24 public void setAge(int age) { 25 this.age = age; 26 } 27 public String getGender() { 28 return gender; 29 } 30 public void setGender(String gender) { 31 this.gender = gender; 32 } 33 @Override 34 public String toString() { 35 return "Person [id=" + id + ", name=" + name + ", age=" + age 36 + ", gender=" + gender + "]"; 37 } 38 public Person(int id, String name, int age, String gender) { 39 super(); 40 this.id = id; 41 this.name = name; 42 this.age = age; 43 this.gender = gender; 44 } 45 public Person() { 46 super(); 47 } 48 49 } Person.java?
2、定義QueryResult用來返回分頁查詢結果集以及表總所有記錄數據的封裝
1 package com.mypro.domain; 2 3 import java.util.List; 4 5 public class QueryResult { 6 7 //返回數據庫中某表總的記錄數 8 private long count; 9 //返回結果集 10 private List list; 11 public long getCount() { 12 return count; 13 } 14 public void setCount(long count) { 15 this.count = count; 16 } 17 public List getList() { 18 return list; 19 } 20 public void setList(List list) { 21 this.list = list; 22 } 23 public QueryResult(long count, List list) { 24 super(); 25 this.count = count; 26 this.list = list; 27 } 28 public QueryResult() { 29 super(); 30 } 31 32 } QueryResult.java?
3、定義Person類和數據庫表的映射關系
1 <?xml version="1.0"?> 2 3 <!DOCTYPE hibernate-mapping PUBLIC 4 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 5 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 6 <hibernate-mapping package="com.mypro.domain"> 7 <class name="Person" table="person"> 8 <id name="id" column="Id" type="int"> 9 <generator class="native"></generator> 10 </id> 11 <property name="name" column="name" type="string"></property> 12 <property name="age" column="Age" type="int"></property> 13 <property name="gender" column="Gender" type="string"></property> 14 </class> 15 </hibernate-mapping> Person.hbm.xml?
二、com.mypro.dao包
1、定一個IPerson的接口,以及接口需要實現的方法
1 package com.mypro.dao; 2 3 import java.util.List; 4 5 import com.mypro.domain.Person; 6 import com.mypro.domain.QueryResult; 7 8 public interface IPerson { 9 10 /** 11 * 添加Person 12 * @param person 13 */ 14 void add(Person person); 15 16 /** 17 * 通過ID刪除Person 18 * @param id 19 */ 20 void delete(int id); 21 22 /** 23 * 修改Person信息 24 * @param person 25 */ 26 void update(Person person); 27 28 /** 29 * 通過ID獲取Person 30 * @param id 31 * @return 32 */ 33 Person get(int id); 34 35 /** 36 * 獲取所有的Person 37 * @return List集合 38 */ 39 List<Person> getAll(); 40 41 /** 42 * 分頁查詢顯示 43 * @param firstResult 第一條記錄從哪里開始 44 * @param maxResults 最多包含多少條記錄 45 * @return 該返回值包含了一個表的總記錄數和一個List結果集 46 */ 47 QueryResult query(int firstResult,int maxResults); 48 49 } IPerson.java?
三、com.mypro.util包
1、定一個HibernateUtils工具類,該類封裝了SessionFactory對象
1 package com.mypro.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 public class HibernateUtils { 8 9 //聲明一個靜態變量,并在靜態代碼塊中給該對象賦值 10 private static SessionFactory sessionFactory; 11 static{ 12 /*方式一 13 Configuration cfg=new Configuration(); 14 cfg.configure("hibernate.cfg.xml"); //加載指定位置的配置 15 sessionFactory=cfg.buildSessionFactory();*/ 16 17 /*方式二:當hibernate的主配置文件名稱為hibernate.cfg.xml時,且該文件在類的根目錄下時,當cfg.configure時可以省略參數 18 Configuration cfg=new Configuration(); 19 cfg.configure(); //加載默認配置文件 20 sessionFactory=cfg.buildSessionFactory();*/ 21 22 //方法三 :由于cfg.configure()方法返回的依然是Configuration對象,所以該方法更進一步精簡為 23 sessionFactory=new Configuration() 24 .configure() 25 .buildSessionFactory(); 26 } 27 28 /** 29 * 獲取SessionFactory工廠 30 * @return 31 */ 32 public static SessionFactory getSessionFactory(){ 33 return sessionFactory; 34 } 35 36 /** 37 * 獲取返回一個打開的Session 38 * @return 39 */ 40 public static Session openSession(){ 41 return sessionFactory.openSession(); 42 } 43 } HibernateUtils.java?
四、com.mypro.dao.impl包
該包主要實現com.mypro.dao下的接口
1、實現IPerson接口
1 package com.mypro.dao.impl; 2 3 import java.util.List; 4 5 import org.hibernate.Query; 6 import org.hibernate.Session; 7 import org.hibernate.Transaction; 8 9 import com.mypro.dao.IPerson; 10 import com.mypro.domain.Person; 11 import com.mypro.domain.QueryResult; 12 import com.mypro.util.HibernateUtils; 13 14 public class PersonImpl implements IPerson { 15 16 @Override 17 public void add(Person person) { 18 Session session=null; 19 Transaction tran=null; 20 try{ 21 session=HibernateUtils.openSession(); 22 tran=session.beginTransaction(); 23 session.save(person); 24 tran.commit(); 25 }catch(RuntimeException e){ 26 if(tran!=null) 27 tran.rollback(); 28 throw e; 29 }finally{ 30 if(session!=null) 31 session.close(); 32 } 33 34 } 35 36 @Override 37 public void delete(int id) { 38 Session session=null; 39 Transaction tran=null; 40 try{ 41 session=HibernateUtils.openSession(); 42 tran=session.beginTransaction(); 43 Person person=session.get(Person.class, id); 44 session.delete(person); 45 tran.commit(); 46 }catch(RuntimeException e){ 47 if(tran!=null) 48 tran.rollback(); 49 throw e; 50 }finally{ 51 if(session!=null) 52 session.close(); 53 } 54 55 } 56 57 @Override 58 public void update(Person person) { 59 Session session=null; 60 Transaction tran=null; 61 try{ 62 session=HibernateUtils.openSession(); 63 tran=session.beginTransaction(); 64 session.update(person); 65 tran.commit(); 66 }catch(RuntimeException e){ 67 if(tran!=null) 68 tran.rollback(); 69 throw e; 70 }finally{ 71 if(session!=null) 72 session.close(); 73 } 74 75 } 76 77 @Override 78 public Person get(int id) { 79 Session session=null; 80 try{ 81 session=HibernateUtils.openSession(); 82 return session.get(Person.class, id); 83 }catch(RuntimeException e){ 84 throw e; 85 }finally{ 86 if(session!=null) 87 session.close(); 88 } 89 } 90 91 @Override 92 public List<Person> getAll() { 93 Session session=null; 94 try{ 95 session=HibernateUtils.openSession(); 96 /*方式一 97 Query query= session.createQuery("FROM persion",,Person.class); 98 return query.list(); */ 99 //方式二 100 return session.createQuery("from Person").list(); //注意HSL方式要求Person為類名,屬性名和類名必須完全一致,其它關鍵字可忽略大小寫 101 }catch(RuntimeException e){ 102 throw e; 103 }finally{ 104 if(session!=null) 105 session.close(); 106 } 107 } 108 109 @Override 110 public QueryResult query(int firstResult, int maxResults) { 111 Session session=null; 112 try{ 113 session=HibernateUtils.openSession(); 114 long count= (long)session.createQuery("SELECT COUNT(*) FROM Person").uniqueResult(); 115 List list=session.createQuery("FROM Person")// 116 .setFirstResult(firstResult)// 117 .setMaxResults(maxResults) 118 .list(); 119 return new QueryResult(count, list); 120 }catch(RuntimeException e){ 121 throw e; 122 }finally{ 123 if(session!=null) 124 session.close(); 125 } 126 } 127 128 } PersonImpl.java?
五、配置hibernate主配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory name="mysqldb"> 7 8 <!-- 配置方言:選擇數據庫類型 --> 9 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 10 11 <!-- 配置數據庫連接信息 --> 12 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 13 <property name="connection.url">jdbc:mysql:///test?characterEncoding=utf8</property> 14 <property name="connection.username">root</property> 15 <property name="connection.password">123456</property> 16 17 <!-- 允許顯示sql語句 --> 18 <property name="show_sql">true</property> 19 <!-- 導入映射文件 --> 20 <mapping resource="com/mypro/domain/Person.hbm.xml" /> 21 </session-factory> 22 </hibernate-configuration> hibernate.cfg.xml?
六、代碼測試
1、在com.mypro.test包下PersonTest.java
1 package com.mypro.test; 2 3 import java.util.List; 4 5 import org.junit.Test; 6 7 import com.mypro.dao.IPerson; 8 import com.mypro.dao.impl.PersonImpl; 9 import com.mypro.domain.Person; 10 import com.mypro.domain.QueryResult; 11 12 public class PersonTest { 13 14 private static IPerson personDao=new PersonImpl(); 15 16 @Test 17 public void add(){ 18 Person person=new Person(); 19 person.setName("zhh"); 20 person.setAge(26); 21 person.setGender("女"); 22 personDao.add(person); 23 } 24 25 @Test 26 public void get(){ 27 Person person=personDao.get(37); 28 System.out.println(person); 29 } 30 31 @Test 32 public void update(){ 33 Person person=personDao.get(37); 34 person.setAge(25); 35 personDao.update(person); 36 } 37 38 @Test 39 public void getAll(){ 40 List<Person> list=personDao.getAll(); 41 for (Person person : list) { 42 System.out.println(person); 43 } 44 } 45 46 @Test 47 public void query(){ 48 QueryResult qr= personDao.query(2, 10); 49 System.out.println("總記錄數:"+qr.getCount()); 50 List<Person> list=qr.getList(); 51 for (Person person : list) { 52 System.out.println(person); 53 } 54 } 55 56 @Test 57 public void delete(){ 58 personDao.delete(37); 59 } 60 } PersonTest.java?
轉載于:https://www.cnblogs.com/caoyc/p/5594789.html
總結
以上是生活随笔為你收集整理的Hibernate CRUD操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows server 2003
- 下一篇: hdu 4502(DP)