一、概述
Hibernate是一個開放源碼的對象關系映射框架,它對JDBC進行了非常輕量級的對象封裝,使我們可以使用對象的編程思維來操作數據庫。
二、配置准備
IDE:Eclipse
下載Jar包:
三、配置步驟
1、創建新的Java項目
2、建立用戶庫-hibernate,引入相應的jar包
- 項目右鍵-build path->configue build path->add library
- 選擇user library,在其中新建library,命名為Hibernate
- 在該library中加入Hibernate所需要的jar包
3、引入mysql的驅動包
4、在mysql中建立相應的數據庫以及表
5、建立Hibernate配置文件hibernate.cfg.xml
這部分可以從參考文檔中拷貝,然后修改對應的數據庫連接。eg:
<?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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">281889</property> <!-- JDBC connection pool (use the built-in) --> <!-- <property name="connection.pool_size">1</property> --> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!-- <property name="hbm2ddl.auto">update</property> --> <mapping resource="com/test/demo/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
6、建立一個類
這個類表示我們想要存儲在數據庫的事件。這個類使用JavaBean標准命getter和setter方法以及字段。雖然這是推薦的設計,但它不是必需的。Hibernate也可以直接訪問字段,訪問器方法的好處是重構的魯棒性。eg:
package com.test.demo; public class Student { private int id; private String name; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
7、建立Student的映射文件Student.hbm.xml
Hibernate需要知道怎樣去加載和存儲持久化類的對象。這正是Hibernate映射文件發揮作用的地方。映射文件告訴Hibernate它,應該訪問數據庫(database)里面的哪個表(table)及應該使用表里面的哪些字段(column)。這部分可以參考文檔。
<?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 package="com.test.demo"> <class name="Student"> <id name="id"></id> <property name="name"></property> <property name="age"></property> </class> </hibernate-mapping>
8、將映射文件加入到Hibernate.cfg.xml文件中,參考文檔
<mapping resource="com/test/demo/Student.hbm.xml"/>
9、寫測試類StudentTest,對student對象進行直接的存儲測試
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class StudentTest { public static void main(String[] args) { Student s = new Student(); s.setId(2); s.setName("s2"); s.setAge(25); Configuration cfg=new Configuration(); SessionFactory sf=cfg.configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); session.save(s); //提交事物 session.getTransaction().commit(); session.close(); sf.close(); } }
執行上述測試程序,結果如下:
四、注釋版本的配置步驟
1、創建Teacher表,並創建相應字段
2、在hibernate lib中加入annotation的jar包
3、創建Teacher類,並參考文檔生成相應的注解
import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Teacher { private int id; private String name; private String title; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
4、在hibernate.cfg.xml文檔中建立映射
<mapping class="com.test.demo.Teacher"/>
5、寫測試類TeacherTest,對Teacher對象進行存儲測試
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; public class TeacherTest { public static void main(String[] args) { Teacher t=new Teacher(); t.setId(2); t.setName("t2"); t.setTitle("初級"); Configuration cfg=new AnnotationConfiguration(); SessionFactory sf=cfg.configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); session.save(t); //提交事物 session.getTransaction().commit(); session.close(); sf.close(); } }
運行上述程序,結果為:
五、配置細節
1、配置hibernate.hbm2ddl.auto
<property name="hbm2ddl.auto">update</property>
這個屬性標簽中有四個參數可以寫,分別是validate|update|create|create drop,對數據庫中進行不同的操作。
validate:每次加載hibernate時,驗證創建數據庫表結構,只會和數據庫中的表進行比較,不會創建新表,但會插入新值
update:第一次加載hibernate時根據model類自動建立表的結構,以后加載hibernate時根據model類自動更新表結構
create:每一次加載hibernate都會刪除上一次生成的表,然后根據你的model類重新生成新表
create drop:每次加載hibernate時根據model類生成表,但是sessionFactor一關閉,表就自動刪除
2、表名和類名不同,對表名進行配置
在類定義之前加上@Table(name="表名")
@Entity @Table(name="People") public class Person { private Long id; private int age; private String name;
這里類名是Person,@Table注釋內為People,運行后,數據庫內表名為:
3、字段名和屬性名不同時
在屬性get方法方法前面加上@Column(name="字段名")
public void setAge(int age) { this.age = age; } @Column(name="PersonName") public String getName() { return name; } public void setName(String name) { this.name = name; }
這里屬性名是name,@Column注釋為PeopleName,運行后該字段名為:
4、設置字段不保存在數據庫中
在該屬性的get方法前面加上@Transient注釋
5、映射日期和時間類型,指定時間精度
Annotation:@Temporal(參數) 參數有3種 只顯示時間,只顯示日期,時間日期都顯示
//@Temporal(TemporalType.DATE) 只顯示日期 //@Temporal(TemporalType.TIME) 只顯示時間 //@Temporal(TemporalType.TIMESTAMP) 顯示日期與時間