Hibernate是在JDBC之上封装了一层便捷性操作的轻量型框架,各有所长。操作便捷性来说当然是Hibernate,但是在JDBC的基础上封装导致了他在扩展性方面有所欠缺。关键看项目的要求,合适才是做好的。下图简单介绍了Hibernate和JDBC操作数据库的流程图。
Java中的java.sql包提供了JDBC常用的接口和类,主要有:
- DriverManager:驱动管理器,负责创建数据库连接;
- Connection:数据库连接;
- Statement:负责执行SQL语句;
- preparedStatement:负责执行SQL语句,具有预定义SQl语句的功能;
- ResultSet:表示SQL查询语句的查询结果集;
Hibernate的核心接口:
- Configuration接口:配置并启动Hibernate,创建SessionFactory对象;
- SessionFactory接口:初始化Hibernate,充当数据存储源的代理,创建Session对象;
- Session接口:负责保存、更新、删除、加载和查询对象;
- Transaction:管理事务;
- Query和Criteria接口:执行数据库查询;
Hibernate操作数据库的主要步骤:
1、新建Web工程;
2、添加Hibernate Jar包,添加数据库驱动Jar包;
3、创建数据表和对象的实体类;
4、配置hibernate.cfg.xml文件,连接数据库
5、配置实体类和数据表的映射关系(可通过XML配置文件,也可通过注解方式);
6、创建SessionFactory工厂类
7、获取Session,进行增删改查操作。
下面以实例说明,例子中就给出主要部分的源码。
Hibernate连接数据的配置文件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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="myeclipse.connection.profile">
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:@192.168.1.26:1521:orcl
</property>
<property name="connection.username">test</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="show_sql">true</property>
<mapping class="bean.CsTUser" />
</session-factory>
</hibernate-configuration>
1、HibernateSessionFactory通过工厂模式实例化SessionFactory,提供了静态方法getSession来获取Session。
package service;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
2、实体类(数据库中要创建相应的数据表,通过注解的方式实现对象关系映射)
package bean;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* CsTUser entity. @author MyEclipse Persistence Tools
*/
@Entity
@Table(name = "CS_T_USER", schema = "ELEVATOR_TEST")
public class CsTUser implements java.io.Serializable {
// Fields
private int FUserId;
private String FVarUsername;
private String FVarPassword;
private String FVarName;
private String FVarPhone;
private String FVarAddress;
private String FVarEmail;
private String FVarSex;
private String FVarZt;
private Date FDtLoadtime;
// Constructors
/** default constructor */
public CsTUser() {
}
/** minimal constructor */
public CsTUser(String FVarUsername, String FVarPassword) {
this.FVarUsername = FVarUsername;
this.FVarPassword = FVarPassword;
}
/** full constructor */
public CsTUser(String FVarUsername, String FVarPassword, String FVarName,
String FVarPhone, String FVarAddress, String FVarEmail,
String FVarSex, String FVarZt, Date FDtLoadtime) {
this.FVarUsername = FVarUsername;
this.FVarPassword = FVarPassword;
this.FVarName = FVarName;
this.FVarPhone = FVarPhone;
this.FVarAddress = FVarAddress;
this.FVarEmail = FVarEmail;
this.FVarSex = FVarSex;
this.FVarZt = FVarZt;
this.FDtLoadtime = FDtLoadtime;
}
// Property accessors
@Id
@GeneratedValue
@Column(name = "F_USER_ID", unique = true, nullable = false, precision = 22, scale = 0)
public int getFUserId() {
return this.FUserId;
}
public void setFUserId(int i) {
this.FUserId = i;
}
@Column(name = "F_VAR_USERNAME", nullable = false, length = 50)
public String getFVarUsername() {
return this.FVarUsername;
}
public void setFVarUsername(String FVarUsername) {
this.FVarUsername = FVarUsername;
}
@Column(name = "F_VAR_PASSWORD", nullable = false, length = 50)
public String getFVarPassword() {
return this.FVarPassword;
}
public void setFVarPassword(String FVarPassword) {
this.FVarPassword = FVarPassword;
}
@Column(name = "F_VAR_NAME", length = 50)
public String getFVarName() {
return this.FVarName;
}
public void setFVarName(String FVarName) {
this.FVarName = FVarName;
}
@Column(name = "F_VAR_PHONE", length = 50)
public String getFVarPhone() {
return this.FVarPhone;
}
public void setFVarPhone(String FVarPhone) {
this.FVarPhone = FVarPhone;
}
@Column(name = "F_VAR_ADDRESS", length = 50)
public String getFVarAddress() {
return this.FVarAddress;
}
public void setFVarAddress(String FVarAddress) {
this.FVarAddress = FVarAddress;
}
@Column(name = "F_VAR_EMAIL", length = 40)
public String getFVarEmail() {
return this.FVarEmail;
}
public void setFVarEmail(String FVarEmail) {
this.FVarEmail = FVarEmail;
}
@Column(name = "F_VAR_SEX", length = 10)
public String getFVarSex() {
return this.FVarSex;
}
public void setFVarSex(String FVarSex) {
this.FVarSex = FVarSex;
}
@Column(name = "F_VAR_ZT", length = 5)
public String getFVarZt() {
return this.FVarZt;
}
public void setFVarZt(String FVarZt) {
this.FVarZt = FVarZt;
}
@Temporal(TemporalType.DATE)
@Column(name = "F_DT_LOADTIME", length = 7)
public Date getFDtLoadtime() {
return this.FDtLoadtime;
}
public void setFDtLoadtime(Date FDtLoadtime) {
this.FDtLoadtime = FDtLoadtime;
}
}
3、测试单元,简单实现Hibernate的Query。
package dao;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import bean.CsTUser;
import service.HibernateSessionFactory;
public class Testhibernate {
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory sessionFactory = HibernateSessionFactory.getSessionFactory();
Session session = sessionFactory.openSession();
List<CsTUser> userList = session.createQuery("from CsTUser").list();
System.out.println(userList.size());
Iterator it = userList.iterator();
while(it.hasNext()){
CsTUser user = (CsTUser) it.next();
System.out.println("username=" + user.getFVarName());
}
session.close();
sessionFactory.close();
}
}