1. 環境配置
1.1 hiberante環境配置
hibernate可實現面向對象的數據存儲。hibernate的官網:http://hibernate.org/ 官網上選擇hibernate ORM,可以下載最新的hibernate,還有配套的document教程 http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/ 。下載到的hibernate文件夾中有document文檔(hibernate\documentation\manual\en-US\html_single)。發現hibernate4.3.1的文件夾中的文檔和網站上提供的答案不太一樣,官網的文檔更詳細一些,還附有toturial的源代碼。
打開eclipse->windows->preferences->java->build path->user libraries,點擊new,新建一個library,可取名為hibernate。點擊Add JARs,選擇hibernate->lib->required中的所有jar文件,另外還需要加上數據庫的connector文件。因為使用的是mysql,所以我這里用到的mysql-connector-java的jar文件。這個jar文件從哪里得到呢?安裝mysql服務器產生的文件夾里面是沒有jar文件的。我們需要另下載一個MySQL的JDBC jar包。可以從mysql的官網上下載:http://dev.mysql.com/downloads/connector/j/ 下載后得到一個msi文件,雙擊及可安裝。安裝后,默認會產生文件夾C:\Program Files (x86)\MySQL\MySQL Connector J ,這里就有一個mysql-connector-java-x.x.x-bin.jar包了。
1.2 mysql數據庫配置
安裝mysql服務器,設置root的密碼為root。啟動mysql服務器,新建數據庫hibernate,並新建表student。
# mysql -uroot -proot > create database hiberante; > use hibernate; > create table student(id int primary key, name varchar(20), age int); > quit;
2. 實例代碼
新建一個java工程,假設取名為HibernateHelloWorld。在src下新那一個package,可取名為com.sun.hibernate.model
2.1 類代碼
新建一個簡單的類,放在com.sun.hibernate.model包下。內容如下:
package com.sun.hibernate.model;
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;
}
}
2.2 配置hibernate配置文件
hibernate\projec\etc中的hiberante.cfg.xml可以作為hibernate的配置文檔,或者可使用hibernate\documentation\manual\en-US\html_single\index.html作為模板。在src文件夾下新建一個文件,並命名為hibernate.cfg.xml。(不可命名為其他文件名)最基礎的配置文件可參考如下:
<?xml version='1.0' encoding='utf-8'?>
<!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>
<!-- 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">root</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>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Enable Hibernate's automatic session context management -->
<!--<property name="current_session_context_class">thread</property>-->
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">create</property> -->
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<mapping resource="com/sun/hibernate/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
mapping resource處的值可根據包名和類名做修改。若類名為Student,則此處的類配置文件必為:Student.hbm.xml。
2.3 類mapping文件
新建一個文件,命名為Student.hbm.xml,放在com.sun.hibernate.model包下。內容如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.sun.hibernate.model"> <class name="Student"> <id name="id"></id> <property name="name"></property> <property name="age"></property> </class> </hibernate-mapping>
注意文件開始處的配置,此處與hibernate.cfg.xml不一樣。如果配置的與hiberante.cfg.xml一樣,運行時會提示錯誤:“文檔根元素 "hibernate-mapping" 必須匹配 DOCTYPE 根 "hibernate-configuration" ”
2.4 StudentTest測試類
新增Student.java的junit測試類StudentTest.java,放在com.sun.hibernate.model包下代碼如下:
package com.sun.hibernate.model;
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(1);
s.setName("s1");
s.setAge(1);
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();
}
}
2.5. 運行結果
運行StudentTest.java這個類,雖然提示輸入成功。去數據庫查詢后,可發現數據已存儲到student數據表中。雖然myeclipse會提示buildSessionFactory()這個函數被deprecated,但實際上程序還是可以運行成功的。
3. 使用annotation
因為使用annotation比較方便,使用annotation就可以不用寫XXX.hbm.xml文件了。
3.1 新建類
敲@后應該出現提示的,如果沒有出現,在Window->Preferences->Java->Editor->Content Assist,在Auto activation triggers forJava中增加@即可。Teacher.java類與Student類內容基本相同,以@開頭的內容為annotation。
package com.sun.hibernate.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Teacher { @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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getTitle() { return title; } public void setTitle(String title) { this.title = title; } private int id; private String name; private int age; private String title; }
3.2 更新hibernate.cfg.xml
在原hibernate.cfg.xml文件的mapping以下標紅內容。
<mapping resource="com/sun/hibernate/model/Student.hbm.xml"/>
<mapping class="com.sun.hiberante.model.Teacher"/>
4.3 新建TeacherTest.java類
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(1);
t.setName("t1");
t.setAge(1);
t.setTitle("middel");
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();
}
}
3.3 運行
在數據庫中新建teacher數據表:
# mysql -uroot -proot > use hibernate; > create table teacher(id int primary key, name varchar(20), age int, title varchar(20)); > quit;
運行TeacherTest.java這個類,雖然提示輸入成功。去數據庫查詢后,可發現數據已存儲到teacher數據表中。
