一、操作步骤
1.创建主配置文件并加载
2.根据主配置文件创建SessionFactory对象
3.根据SessionFactory对象创建Session对象
4.根据Session对象开启事务
5.执行操作
6.提交事务
7.释放资源
二、工具类
SessionFactory使用原则:一个应用一般只有一个SessionFactory(线程安全),应用加载时创建(不影响效率),应用卸载时销毁。所以可以创建一个工具类
package com.tfrunning.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/*
* 抽取Hibernate工具类
* */
public class HibernateUtils {
private static SessionFactory factory;
//Hibernate把可预见的异常都转成了运行时异常
static {
try {
Configuration cfg = new Configuration();
cfg.configure();
factory = cfg.buildSessionFactory();
} catch (ExceptionInInitializerError e) {
// TODO Auto-generated catch block
throw new ExceptionInInitializerError("初始化SessionFactory失败,请检查配置文件");
}
}
//获取一个新的Session对象
public static Session openSession(){
return factory.openSession();
}
}
三、CRUD操作
package test;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.tfrunning.domain.Customer;
import com.tfrunning.utils.HibernateUtils;
/*
* Hibernate的CRUD
* */
public class HibernateDemo3 {
/*
* 增
* */
@Test
public void testAdd(){
Customer customer = new Customer();
customer.setCustName("同方1");
customer.setCustPhone("88881");
customer.setCustSource("网络1");
customer.setCustLevel("VIP1");
customer.setCustIndustry("IT1");
customer.setCustAddress("大连1");
Session session = HibernateUtils.openSession();
Transaction tr = session.beginTransaction();
session.save(customer);
tr.commit();
session.close();
}
/*
* 删
* */
@Test
public void testDelete(){
Session session = HibernateUtils.openSession();
Transaction tr = session.beginTransaction();
Customer c = session.get(Customer.class, 1L);
session.delete(c);
tr.commit();
session.close();
}
/*
* 改
* */
@Test
public void testUpdate(){
Session session = HibernateUtils.openSession();
Transaction tr = session.beginTransaction();
Customer c = session.get(Customer.class, 4L);
session.update(c);
tr.commit();
session.close();
}
/*
* 查一个
* */
@Test
public void testSelect(){
Session session = HibernateUtils.openSession();
Transaction tr = session.beginTransaction();
Customer c = session.get(Customer.class, 5L);
System.out.println(c);
tr.commit();
session.close();
}
/*
* 查多个
* */
@Test
public void testFindAll(){
Session session = HibernateUtils.openSession();
Transaction tr = session.beginTransaction();
//使用session对象获取一个查询对象Query
SQLQuery query = session.createSQLQuery("select * from cst_customer");
//使用query获取结果集
List<Object[]> list = query.list();
for(Object[] o :list){
System.out.println("数组中的内容————————————————————————————————————");
for(Object os:o){
System.out.println(os);
}
}
tr.commit();
session.close();
}
}