public class HibernateSessionFactory {
private static SessionFactory factory;
private static ThreadLocal<Session> thread = new ThreadLocal<Session>();
private static String path = "hibernate.cfg.xml";
private static Configuration config = new Configuration();
static {
config.configure(path);
ServiceRegistry service = new ServiceRegistryBuilder()//定义一个服务注册机
.applySettings(config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(service);//创建Session工厂类
}
public static Session getSession() {
Session session = thread.get();
if(session == null || !session.isOpen()) {
session = factory.openSession();
thread.set(session);
}
return session;
}
public static void closeSession() {
Session session = thread.get();
if(session != null && session.isOpen()) {
session.close();
thread.set(null);
}
}
}
DAO层封装数据各项操作的方法
package demo.dao;
import java.io.Serializable;
import org.hibernate.Session;
import org.hibernate.Transaction;
import demo.pojo.Person;
import demo.util.HibernateSessionFactory;
public class PersonDaoImpl {
//增删改查,此处以增为例
public boolean add(Person p) {
Session session = HibernateSessionFactory.getSession();//创建Session
Transaction trans = session.beginTransaction();//开启事务
try {
Serializable id = session.save(p);//添加记录并获取主键值
System.out.println(id+"为获取的主键值");//控制台查看主键值
trans.commit();//提交事务
return true;
} catch (Exception e) {
trans.rollback();//获取异常,则事务回滚
} finally {
HibernateSessionFactory.closeSession();//关闭Session
}
return false;
}
}
测试类TestPerson
package demo.test;
import org.junit.Test;
import demo.dao.PersonDaoImpl;
import demo.pojo.Person;
public class TestPerson {
@Test
public void testAdd() {
//创建一个人类对象
Person p = new Person();
p.setName("张三");
p.setGender("男");
p.setAge(18);
//创建dao层类对象并调用添加方法
PersonDaoImpl dao = new PersonDaoImpl();
dao.add(p);
}
}
Hibernate利用@DynamicInsert和@DynamicUpdate生成动态SQL语句