1. 程式人生 > >【Hibernate】——實體類對映到資料庫表

【Hibernate】——實體類對映到資料庫表

    上回說到, Hibernate是一個開放原始碼的物件關係對映框架,其核心應該也就是映射了,所以,今天我們瞭解一下Hibernate是如何將實體和資料庫對映的。--即Hibernate根據實體自動建立表和欄位。

    為了讓大家更明瞭,小編寫了一個小demo。實現了將實體對映到資料庫表。希望通過這個小程式,讓大家有所收穫。

    先巨集觀看一下目錄結構:


    首先是Hibernate的核心配置檔案:hibernate.cfg.xml

<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
	</session-factory>
</hibernate-configuration>
這是一個連線MySQL的示例,若想換資料庫,直接更改此配置檔案即可,程式碼無需改動,這也是Hibernate的優點之一。
    然後,開始建立實體類,其包括5個屬性:
package com.bjpowernode.hibernate;

import java.util.Date;

public class User {
	private String id;
	private String name;
	private String password;
	private Date createTime;
	private Date expireTime;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public Date getExpireTime() {
		return expireTime;
	}
	public void setExpireTime(Date expireTime) {
		this.expireTime = expireTime;
	}

}
    隨後,建立 User.hbm.xml,完成實體類的對映。(其中的註釋資訊可以幫你更好的理解)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.bjpowernode.hibernate.User"> <!-- 實體類完整路徑,會在關係模型中建立一張表,
叫User,也可以用table重新命名,如 table="t_user" -->
		<id name="id"><!--標識主鍵,會在表裡建主鍵id,也可以重新命名 column="user_id"  -->
			<generator class="uuid"/><!--主鍵生成策略,generator為生成器,uuid為生成
不重複的32位字串  -->
		</id>
		<property name="name"/><!--其它屬性,對應欄位  -->
		<property name="password"/>
		<property name="createTime"/>
		<property name="expireTime"/>
	</class>

</hibernate-mapping>
    最後,將User.hbm.xml新增到核心配置檔案hibernate.cfg.xml中。
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		
		<mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/>
	</session-factory>
</hibernate-configuration>
     這樣就完成了,通過這樣的關聯對映,Hibernate將會在資料庫中建立相應的表和欄位。

    為了更好的看到效果,小編建立了ExportDB.java,手動完成

package com.bjpowernode.hibernate;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**
 * 將hbm生成ddl
 * @author han
 *
 */
public class ExportDB {
	public static void main(String[] args){
		//預設讀取hibernate.cfg.xml檔案
		Configuration cfg=new Configuration().configure();//讀配置檔案
		SchemaExport export=new SchemaExport(cfg);//通過此生成ddl
		export.create(true, true);//列印到控制檯,輸出指令碼到資料庫
	}
}
    原庫:


    執行後(插入表、欄位):


    建立Client.java,看插入資料效果

package com.bjpowernode.hibernate;

import java.util.Date;

import javax.lang.model.type.NullType;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Client {

	public static void main(String[] args){
		//預設讀取hibernate.cfg.xml檔案
		Configuration cfg=new Configuration().configure();
		//建立SessionFactory,映象
		SessionFactory factory=cfg.buildSessionFactory();
		
		//取得session
		Session session=null;
		try {
			session=factory.openSession();
			//開啟事務
			session.beginTransaction();
			//建立物件,儲存到資料庫
			User user=new User();
			user.setName("張三");
			user.setPassword("123");
			user.setCreateTime(new Date());
			user.setExpireTime(new Date());
			
			//儲存User物件
			session.save(user);
			//提交事務
			session.getTransaction().commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			//回滾
			session.getTransaction().rollback();
			
		}finally{
			if(session!=null)
				if (session.isOpen()) {
					//關閉session
					session.close();
				}
		}
		
		
	}
}

    通過這個例子,我們看到,Hibernate可以將實體類對映到資料庫。從實體類到建表,設計欄位到插入資料,我們沒有寫任何的SQL語句,因為Hibernate對底層做了很大程度的封裝,省去了我們寫SQL的這些過程。當然,這有利也有弊。弊就是由於封裝的太嚴密,喪失了某些靈活性......