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配置方式与@注解方式可达到同样的效果,只是@注解方式更为方便,实际编程中多用@注解方式进行配置。