1. 程式人生 > >【Hibernate】搭建一個Hibernate環境,開發步驟

【Hibernate】搭建一個Hibernate環境,開發步驟

搭建一個Hibernate環境,開發步驟:

1. 下載原始碼

版本:hibernate-distribution-3.6.0.Final

2. 引入jar檔案

hibernate3.jar核心  +  required 必須引入的(6個) +  jpa 目錄  + 資料庫驅動包

3. 寫物件以及物件的對映

Employee.java            物件

Employee.hbm.xml        物件的對映 (對映檔案)

4. src/hibernate.cfg.xml  主配置檔案

-à 資料庫連線配置

-à 載入所用的對映(*.hbm.xml)

5. App.java  測試

Employee.java     物件

//一、 物件
public class Employee {

	private int empId;
	private String empName;
	private Date workDate;
	
}

Employee.hbm.xml  物件的對映

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.lfsenior.a_hello">
	
	<class name="Employee" table="employee">
		
		<!-- 主鍵 ,對映-->
		<id name="empId" column="id">
			<generator class="native"/>
		</id>
		
		<!-- 非主鍵,對映 -->
		<property name="empName" column="empName"></property>
		<property name="workDate" column="workDate"></property>
		
	</class>

</hibernate-mapping>

hibernate.cfg.xml    主配置檔案

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/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:///hib_demo</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		
		<property name="hibernate.show_sql">true</property>
		
		<!-- 載入所有對映 -->
		<mapping resource="cn/lfsenior/a_hello/Employee.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

App.java   測試類

public class App {

	@Test
	public void testHello() throws Exception {
		// 物件
		Employee emp = new Employee();
		emp.setEmpName("班長");
		emp.setWorkDate(new Date());
		
		// 獲取載入配置檔案的管理類物件
		Configuration config = new Configuration();
		config.configure();  // 預設載入src/hibenrate.cfg.xml檔案
		// 建立session的工廠物件
		SessionFactory sf = config.buildSessionFactory();
		// 建立session (代表一個會話,與資料庫連線的會話)
		Session session = sf.openSession();
		// 開啟事務
		Transaction tx = session.beginTransaction();
		//儲存-資料庫
		session.save(emp);
		// 提交事務
		tx.commit();
		// 關閉
		session.close();
		sf.close();
	}
}