五、通过
Hibernate API
操纵数据库
例:
BusinessService.java
package mypack;
import javax.servlet.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import java.io.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;
public class BusinessService{
public static SessionFactory sessionFactory;
/**
初始化
Hibernate
,创建
SessionFactory
实例
*/
static{
try{
// Create a configuration based on the properties file we've put
// in the standard place.
Configuration config = new Configuration();
config.addClass(Customer.class);
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
}catch(Exception e){e.printStackTrace();}
}
public void findAllCustomers(ServletContext context,OutputStream out) throws Exception{
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List customers=session.find("from Customer as c order by c.name asc");
for (Iterator it = customers.iterator(); it.hasNext();) {
printCustomer(context,out,(Customer) it.next());
}
// We're done; make our changes permanent
tx.commit();
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public void saveCustomer(Customer customer) throws Exception{
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.save(customer);
// We're done; make our changes permanent
tx.commit();
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public void loadAndUpdateCustomer(Long customer_id,String address) throws Exception{
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Customer c=(Customer)session.load(Customer.class,customer_id);
c.setAddress(address);
// We're done; make our changes permanent
tx.commit();
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
public void deleteAllCustomers() throws Exception{
// Ask for a session using the JDBC information we've configured
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete("from Customer as c");
// We're done; make our changes permanent
tx.commit();
}catch (Exception e) {
if (tx != null) {
// Something went wrong; discard all partial changes
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
}
private void printCustomer(ServletContext context,OutputStream out,Customer customer)throws Exception{
if(out instanceof ServletOutputStream)
printCustomer(context,(ServletOutputStream) out,customer);
else
printCustomer((PrintStream) out,customer);
}
private void printCustomer(PrintStream out,Customer customer)throws Exception{
//save photo
byte[] buffer=customer.getImage();
FileOutputStream fout=new FileOutputStream("photo_copy.gif");
fout.write(buffer);
fout.close();
out.println("------
以下是
"+customer.getName()+"
的个人信息
------");
out.println("ID: "+customer.getId());
out.println("
口令
: "+customer.getPassword());
out.println("E-Mail: "+customer.getEmail());
out.println("
电话
: "+customer.getPhone());
out.println("
地址
: "+customer.getAddress());
String sex=customer.getSex()=='M'? "
男
":"
女
";
out.println("
性别
: "+sex);
String marriedStatus=customer.isMarried()? "
已婚
":"
未婚
";
out.println("
婚姻状况
: "+marriedStatus);
out.println("
生日
: "+customer.getBirthday());
out.println("
注册时间
: "+customer.getRegisteredTime());
out.println("
自我介绍
: "+customer.getDescription());
}
private void printCustomer(ServletContext context,ServletOutputStream out,Customer customer)throws Exception{
//save photo
byte[] buffer=customer.getImage();
String path=context.getRealPath("/");
FileOutputStream fout=new FileOutputStream(path+"photo_copy.gif");
fout.write(buffer);
fout.close();
out.println("------
以下是
"+customer.getName()+"
的个人信息
------"+"<br>");
out.println("ID: "+customer.getId()+"<br>");
out.println("
口令
: "+customer.getPassword()+"<br>");
out.println("E-Mail: "+customer.getEmail()+"<br>");
out.println("
电话
: "+customer.getPhone()+"<br>");
out.println("
地址
: "+customer.getAddress()+"<br>");
String sex=customer.getSex()=='M'? "
男
":"
女
";
out.println("
性别
: "+sex+"<br>");
String marriedStatus=customer.isMarried()? "
已婚
":"
未婚
";
out.println("
婚姻状况
: "+marriedStatus+"<br>");
out.println("
生日
: "+customer.getBirthday()+"<br>");
out.println("
注册时间
: "+customer.getRegisteredTime()+"<br>");
out.println("
自我介绍
: "+customer.getDescription()+"<br>");
out.println("<img src='photo_copy.gif' border=0><p>");
}
public void test(ServletContext context,OutputStream out) throws Exception{
Customer customer=new Customer();
customer.setName("Tom");
customer.setEmail("tom@yahoo.com");
customer.setPassword("1234");
customer.setPhone(55556666);
customer.setAddress("Shanghai");
customer.setSex('M');
customer.setDescription("I am very honest.");
InputStream in=this.getClass().getResourceAsStream("photo.gif");
byte[] buffer = new byte[in.available()];
in.read(buffer);
customer.setImage(buffer);
customer.setBirthday(Date.valueOf("1980-05-06"));
saveCustomer(customer);
findAllCustomers(context,out);
loadAndUpdateCustomer(customer.getId(),"Beijing");
findAllCustomers(context,out);
deleteAllCustomers();
}
public static void main(String args[]) throws Exception {
new BusinessService().test(null,System.out);
sessionFactory.close();
}
}
(1)
Hibernate
的初始化
静态代码块负责 Hibernate 的初始化工作,如读取 Hibernate 的配置信息及对象 - 关系映射信息,最后创建 SessionFactory 实例。
初始化过程如下步骤:
a. 创建一个 Configuration 类的实例, Configuration 类的构造方法把默认文件路径下的 hibernate.propertyes 配置文件中的配置信息读入到内存:
Configuration config=new Configuration();
b. 调用 Configuration 类的 addClass(Customer.class) 方法:
config.addClass(Customer.class);
c. 调用 Configuration 类的 buildSessionFactory() 方法:
sessionFactory=config.buildsessionFactory();
该方法创建一个 SessionFactory 实例。 SessionFactory 代表一个数据库存储源,如果应用只有一个数据库存储源,那么只需创建一个 SessionFactory 实例。
当 SessionFactory 对象创建后,该对象不和 Configuration 对象关联。因此,如果再修改 Configuration 对象包含的配置信息,不会对 SessionFactory 对象有任何影响。
PS : Java 语言是纯面向对象的语言,因此不可能像 C 语言那样直接操纵内存,因此若有提到缓存的概念,指的是 java 对象的属性 ( 通常是一些集合类型的属性 ) 占用的内存空间。
如果对象的缓存很大,就称为重量级对象;若很小,就称为轻量级对象。
SessionFactory 的缓存可分为两类:内置缓存和外置缓存 ( 是一个可配置的缓存插件 ) 。
静态代码块负责 Hibernate 的初始化工作,如读取 Hibernate 的配置信息及对象 - 关系映射信息,最后创建 SessionFactory 实例。
初始化过程如下步骤:
a. 创建一个 Configuration 类的实例, Configuration 类的构造方法把默认文件路径下的 hibernate.propertyes 配置文件中的配置信息读入到内存:
Configuration config=new Configuration();
b. 调用 Configuration 类的 addClass(Customer.class) 方法:
config.addClass(Customer.class);
c. 调用 Configuration 类的 buildSessionFactory() 方法:
sessionFactory=config.buildsessionFactory();
该方法创建一个 SessionFactory 实例。 SessionFactory 代表一个数据库存储源,如果应用只有一个数据库存储源,那么只需创建一个 SessionFactory 实例。
当 SessionFactory 对象创建后,该对象不和 Configuration 对象关联。因此,如果再修改 Configuration 对象包含的配置信息,不会对 SessionFactory 对象有任何影响。
PS : Java 语言是纯面向对象的语言,因此不可能像 C 语言那样直接操纵内存,因此若有提到缓存的概念,指的是 java 对象的属性 ( 通常是一些集合类型的属性 ) 占用的内存空间。
如果对象的缓存很大,就称为重量级对象;若很小,就称为轻量级对象。
SessionFactory 的缓存可分为两类:内置缓存和外置缓存 ( 是一个可配置的缓存插件 ) 。
(2)
Hibernate
的许多类和接口都支持方法链编程风格,
Configuration
类的
addClass()
方法返回当前的
Configuration
实例,因此对于以下代码:
Configuration config=new Configuration();
config.addClass(Customer.class);
sessionFactory=config.buildSessionFactory();
如果用方法链编程风格,可以改写为:
sessionFactory=new Configuration()
.addClass(Custormer.class)
.buildSessionFactory();
Configuration config=new Configuration();
config.addClass(Customer.class);
sessionFactory=config.buildSessionFactory();
如果用方法链编程风格,可以改写为:
sessionFactory=new Configuration()
.addClass(Custormer.class)
.buildSessionFactory();
(3)
访问
Hibernate
的
Session
接口
初始化过程结束后,就可以调用 SessionFactory 实例的 openSession() 方法来获取 Session 实例,然后通过它执行访问数据库的操作。
a. save() 方法:把 Java 对象保存数据库中;
b. update() 方法:
c. delete() 方法:
d. load() 方法:从数据库中加载 Java 对象;
e. find() 方法:从数据库中查询 Java 对象。
通常将每一个 Session 实例和一个数据库事务绑定,也就是说,每执行一个数据库事务,都应该先创建一个新的 Session 实例。
如果事务执行中出现异常,应该撤消事务。
无论事务执行成功与否,最后都应该调用 Session 的 close() 方法,从而释放 Session 实例占用的资源。
以下代码演示了用 Session 来执行事务的流程,其中 Transaction 类用来控制事务。
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
// 执行事务
…
// 提交事务
tx.commit();
}catch(Exception e){
// 如果出现异常,则撤销事务
if(tx!=null) tx.rollback();
throw e;
} finally{
// 无论事务执行是否成功,都关闭 Session
session.close();
}
初始化过程结束后,就可以调用 SessionFactory 实例的 openSession() 方法来获取 Session 实例,然后通过它执行访问数据库的操作。
a. save() 方法:把 Java 对象保存数据库中;
b. update() 方法:
c. delete() 方法:
d. load() 方法:从数据库中加载 Java 对象;
e. find() 方法:从数据库中查询 Java 对象。
通常将每一个 Session 实例和一个数据库事务绑定,也就是说,每执行一个数据库事务,都应该先创建一个新的 Session 实例。
如果事务执行中出现异常,应该撤消事务。
无论事务执行成功与否,最后都应该调用 Session 的 close() 方法,从而释放 Session 实例占用的资源。
以下代码演示了用 Session 来执行事务的流程,其中 Transaction 类用来控制事务。
Session session=sessionFactory.openSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
// 执行事务
…
// 提交事务
tx.commit();
}catch(Exception e){
// 如果出现异常,则撤销事务
if(tx!=null) tx.rollback();
throw e;
} finally{
// 无论事务执行是否成功,都关闭 Session
session.close();
}