Hibernate是一種ORM框架,全程爲Object-Relative Database-Mapping,在Java對象與關係數據庫之間建立某種映射,以實現直接存取Java對象(一般爲POJO)。下面就以一個簡單的Hibernate程序來快速瞭解Hibernate。
1.添加Hibernate的Jar包
導入Hibernate必需的核心包hibernate-core-4.1.12.Final.jar;在Hibernate中使用Annonation需要導入ejb3-persistence.jar、hibernate-annotations.jar、hibernate-commons-annonations.jar;本項目中使用的數據庫是Oracle數據庫,因此還需導入ojdbc6.jar,若使用其他類型的數據庫,需導入相應的包。此外,在程序運行過程中報錯,發現少包,因此我按照錯誤一一導入瞭如下這些包:hibernate-jpa-2.0-api-1.0.1.Final.jar、dom4j-1.6.1.jar、jboss-logging-3.1.1.ga.jar、jboss-transaction-api_1.2_spec-1.0.0.Final.jar、lucene-core-3.6.2.jar、javassist-3.15.0-GA.jar。使用的Hibernate版本不同,需要導入的包也會略有不同,可根據程序提示的錯誤一一加入需要的包。
2.配置Student實體類
package com.hibernate.model;
import javax.persistence.Entity;
import javax.persistence.Id;
//聲明爲實體類
@Entity
public class Student {
private String id;
private String name;
private int age;
//配置爲主鍵
@Id
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
此處使用的是@註解方式來配置實體類。使用@Entity配置後,Student類就被聲明爲了一個實體類。實體類還需要配置對應的表名(用@Table配置,此處省略,默認表名與類名相同)、主鍵(用@Id配置)、普通屬性對應的列名(用@Column配置,此處省略,默認列名與屬性名相同)等。
3.修改Hibernate配置文件
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="connection.username">user</property>
<property name="connection.password">pwd</property>
<!-- JDBC connection pool (use the built-in) -->
<!-- <property name="connection.pool_size">1</property>-->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</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.internal.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>-->
<!-- 指定Student類爲Hibernate實體類 -->
<mapping class="com.hibernate.model.Student"/>
</session-factory>
</hibernate-configuration>
hibernate.cfg.xml配置文件中,connection.xxx表示JDBC連接信息;dialect值爲org.hibernate.dialect.Oracle10gDialect,表示使用Oracle的SQL語句(各數據庫的SQL語句會有輕微區別,因此用dialect加以區別,此處也可以省略,因爲可以通過JDBC連接信息自動判斷使用的是何種數據庫);show_sql的值爲true,表示在控制檯顯示生成的SQL語句;最後< mapping class=”” />指定Student類爲Hibernate實體類。其他配置信息暫且未用到,以後再進行詳細介紹。
4.創建實體類對應的數據庫表
SQL> create table student(
2 id varchar2(20) primary key,
3 name varchar2(20),
4 age number);
Table created
SQL> select * from student;
ID NAME AGE
-------------------- -------------------- ----------
5.執行Hibernate程序
package com.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static{
try{
sessionFactory =new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Throwable ex){
System.err.println("初始化SessionFactory創建失敗"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
package com.hibernate.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.hibernate.model.Student;
import com.hibernate.util.HibernateUtil;
public class StudentTest {
public static void main(String[] args) {
Student s=new Student();
s.setId("1");
s.setName("Elana");
s.setAge(23);
// Configuration cfg=new AnnotationConfiguration();
// SessionFactory sf=cfg.configure().buildSessionFactory();
//使用工具類,保證單例
SessionFactory sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
sf.close();
}
}
運行結果:會在控制檯打印出SQL語句,Hibernate: insert into Student (age, name, id) values (?, ?, ?),併成功將數據插入數據庫表中。
SQL> select * from student;
ID NAME AGE
-------------------- -------------------- ----------
1 Elana 23
至此,第一個Hibernate就結束了。此外,也可以使用xml配置實體類,如上例中若不適用@註解方式,則可新建一個xml文件,配置如下:
student.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="com.hibernate.model">
<class name="Student" table="student">
<id name="id" type="string"></id>
<property name="name" type="string"/>
<property name="age" type="int"/>
</class>
</hibernate-mapping>
相應地,hibernate.cfg.xml文件中指定實體類的方式應由< mapping class=”com.hibernate.model.Student” />變爲 < mapping resource=”com/hibernate/model/student.hbm.xml” />。xml配置方式與@註解方式可達到同樣的效果,只是@註解方式更爲方便,實際編程中多用@註解方式進行配置。