1. 程式人生 > >Hibernate使用xml配置持久化類

Hibernate使用xml配置持久化類

Hibernate通過物件關係對映,使用持久化類代替傳統的sql語句對資料庫進行操作(通俗說就是把資料表變成一個實體類來看待和操作)。其中,持久化類可以使用

1.配置對應的hbm.xml(關係對映配置檔案)來對映持久化實體類。

2.直接在持久化實體類以註解方式配置。

前期工作:

一、匯入Hibernate相關依賴包(包括本人使用的mysql驅動包和c3p0連線池依賴包):

二、建立事例表與資料:

xml配置持久化類:

一、首先,先在Hibernate.cfg.xml配置Hibernate啟動相關配置項:

<?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 >  
        <!-- mysql資料庫驅動 -->  
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>  
        <!-- mysql資料庫名稱 -->  
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>  
        <!-- 資料庫的登陸使用者名稱 -->  
        <property name="hibernate.connection.username">root</property>  
        <!-- 資料庫的登陸密碼 -->  
        <property name="hibernate.connection.password">1988419</property>  
        <!-- 配置方言為每一種資料庫提供特殊sql適配-->  
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>  

		<!-- c3p0連線池配置 -->
		<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
		<!-- 連線池最大連線 -->
		<property name="hibernate.c3p0.max_size">10</property>
		<!-- 連線池最小連線 -->
		<property name="hibernate.c3p0.min_size">1</property>
        <!-- 連線池超時時長(毫秒) -->  
        <property name="hibernate.c3p0.timeout">5000</property>
        <!-- 指定連線池最大快取多少Statment物件 -->
        <property name="hibernate.c3p0.max_statment">50</property>
        <!-- 空閒檢測週期(毫秒) -->
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <!-- 連線池一次增加的連線數 -->
        <property name="hibernate.c3p0.acquire_increment">5</property>
        <!-- 每次都驗證連線是否可用 -->
        <property name="hibernate.c3p0.validate">true</property>
        
        <!-- 是否在控制檯輸出sql語句 -->
        <property name="hibernate.show_sql">true</property>
        
        <!-- 使用xml配置時,指定持久化類xml的路徑 -->
        <mapping resource="org/lcwben/Student.hbm.xml"></mapping>
        
        <!-- 使用註解持久化類配置時,指定持久化類.java檔案配置 -->
<!-- 			<mapping class="org.lcwben.Student" /> -->
    </session-factory>  
</hibernate-configuration>  

、建立持久化實體類:

public class Student {

	private Integer uid;
	private String uname;
	private Date regtime;
	private Integer status;
	private Integer score;
	private Integer classes;
	
	
//所有成員變數的getter與setter
	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public Date getRegtime() {
		return regtime;
	}
	public void setRegtime(Date regtime) {
		this.regtime = regtime;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public Integer getScore() {
		return score;
	}
	public void setScore(Integer score) {
		this.score = score;
	}
	public Integer getClasses() {
		return classes;
	}
	public void setClasses(Integer classes) {
		this.classes = classes;
	}
//。。。。。。。。。。。。。。。。。。。。。。。
	
}

三、配置關聯對映xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
      
<hibernate-mapping>  
    <class name="org.lcwben.Student" table="test_stu">
    	<!-- 主鍵使用自增(increment)選項 -->  
        <id name="uid" column="uid">  
            <generator class="increment"/>  
        </id>  
        <property name="uname"/>  
        <property name="regtime"/>  
        <property name="status"/>  
        <property name="score"/>
        <property name="classes"/>
    </class>  
</hibernate-mapping>  

四、JUnit測試
public class Client {
	
	private static SessionFactory sf;
	
	//利用靜態塊初始化連線池
	static {
		//用Configuration類初始化hibernate.cfg.xml的配置項
		Configuration cfg = new Configuration().configure();
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		sf = cfg.buildSessionFactory(sr); 
	}

	//增
	@Test
	public void testCreate() { 
		Session session = null;
		try {
			//開啟session
			session = sf.openSession();
			//開啟事務管理器
			session.beginTransaction();
			Student stu1 = new Student();
			stu1.setUname("hib1");
			stu1.setRegtime(new Date());
			stu1.setStatus(1);
			stu1.setScore(75);
			stu1.setClasses(4);
			session.save(stu1);
			//從session物件取出事務管理器,提交事務;
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			//出異常時對事務進行事務回滾
			session.getTransaction().rollback();
		} finally {
			if(session!=null){
				session.close();				
			}
		}
	}
	
	//刪
	@Test
	public void delete() {
		Session session = null;
		try {
			session = sf.openSession();
			session.beginTransaction();
			Student stu1 = new Student();
			stu1.setUid(12);
			stu1.setUname("hib1");
			stu1.setRegtime(new Date());
			stu1.setStatus(1);
			stu1.setScore(75);
			stu1.setClasses(4);
			session.delete(stu1);
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			if(session!=null) {
				session.close();
			}
		}
	}
	
	//全量查詢
	@Test
	public void selectAll() {
		Session session = null;
		List<Student> stus = null;
		try {
			session = sf.openSession();
			session.beginTransaction();
			//注意:HQL中的表名並非資料庫中的表名,而是對應對映物件類的類名!!!
			Query query1 = session.createQuery("from Student");
			stus = query1.list();
			for (Student stu : stus) {
				System.out.println(stu.getUid()+" "+stu.getUname()+" "+stu.getRegtime()+" "+stu.getStatus()+" "+stu.getScore()+" "+stu.getClasses());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session!=null) {
				session.close();
			}
		}

	}
	
	//條件查詢
	@Test
	public void selectOne() {
		Session session = null;
		try {
			session = sf.openSession();
			Query query = session.createQuery("from Student where uid=:id");
			query.setInteger("id", 3);
			Student stu = (Student)query.uniqueResult();
			System.out.println(stu.getUid()+" "+stu.getUname()+" "+stu.getRegtime()+" "+stu.getStatus()+" "+stu.getScore()+" "+stu.getClasses());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session!=null) {
				session.close();
			}
		}
	}
	
	//改
	@Test
	public void update () {
		Session session = null;
		try {
			session = sf.openSession();
			session.beginTransaction();
			String hql = "update Student set uname=:name where uid=:id";
			Query qry = session.createQuery(hql);
			qry.setString("name", "lcwhbm1");
			qry.setInteger("id", 4);
			qry.executeUpdate();
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			if (session!=null) {
				session.close();
			}
		}
	}

	//改
	@Test
	public void update2 () {
		Session session = null;
		try {
			session = sf.openSession();
			session.beginTransaction();
			/*使用load(持久化類物件, 主鍵值)的方式直接獲得條件所指的物件,
			 * 代替了select... where pk=...的形式,不需要寫sql語句就可以實現條件查詢的功能。
			 */
			Student stu = (Student)session.load(Student.class, 4);
			//然後使用持久化類的setter可以對該條資料進行修改!
			stu.setUname("benhbm2");
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		} finally {
			if (session!=null) {
				session.close();
			}
		}
	}
以下給出的是selectAll()的查詢結果:
三月 08, 2017 2:35:48 下午 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
三月 08, 2017 2:35:48 下午 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select student0_.uid as uid1_0_, student0_.uname as uname2_0_, student0_.regtime as regtime3_0_, student0_.status as status4_0_, student0_.score as score5_0_, student0_.classes as classes6_0_ from test_stu student0_
1 lcwben1 2017-01-18 00:00:00.0 0 60 1
2 lcwben2 2017-01-18 00:00:00.0 1 67 1
3 lcwben3 2017-01-19 00:00:00.0 1 51 3
4 benhbm2 2017-01-19 00:00:00.0 0 78 3
5 lcwben5 2017-01-19 00:00:00.0 0 80 3
6 lcwben6 2017-01-22 00:00:00.0 1 97 2
7 lcwben7 2017-01-23 00:00:00.0 0 73 1
8 lcwben8 2017-01-25 00:00:00.0 1 48 2
9 lcwben9 2017-01-28 00:00:00.0 1 100 3
10 lcwben10 2017-01-31 00:00:00.0 0 92 3

至於註解式配置持久化類,由於篇幅所限,另開一篇文章(點選開啟連結)。