package cn.com.bochy.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUntil<T> {
private SessionFactory sf;
private Session session;
@SuppressWarnings("deprecation")
//1、获取SessionFactory
public SessionFactory getSF(){
//读取Hibernate配置文件
Configuration cfg=new Configuration().configure();
//获取SessionFactory
sf=cfg.buildSessionFactory();
return sf;
}
//2、获取session
public Session getSession(){
getSF();
session=sf.openSession();
return session;
}
@SuppressWarnings("unchecked")
//3、封装成list
public List<T> getList(String hql){
getSession();
Query query=session.createQuery(hql);
List<T> lis=query.list();
closeAll();
return lis;
}
//4、添加
public boolean Save(T obj){
getSession();
Transaction tx=session.beginTransaction();
boolean mark=true;
try {
session.save(obj);
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
mark=false;
e.printStackTrace();
tx.rollback();
}
closeAll();
return mark;
}
//5、修改
public boolean update(T obj){
getSession();
Transaction tx=session.beginTransaction();
boolean mark=true;
try {
session.saveOrUpdate(obj);
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
mark=false;
e.printStackTrace();
tx.rollback();
}
closeAll();
return mark;
}
//6、根据id,获取实体对象
public T getObjectById(int id,Class<T> c){
getSession();
@SuppressWarnings("unchecked")
T obj=(T)session.get(c, id);
closeAll();
return obj ;
}
//7、删除
public boolean delete(T obj){
getSession();
Transaction tx=session.beginTransaction();
boolean mark=true;
try {
session.delete(obj);
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
mark=false;
e.printStackTrace();
tx.rollback();
}
closeAll();
return mark;
}
//8、关闭资源
public void closeAll(){
if(session!=null){
session.close();
}
if(sf!=null){
sf.close();
}
}
}
相关文章
- UI 组件的二次封装
- 使用 Hibernate 和 MySQL 需要知道的五件事
- spring中xml的解析与beanDefinition封装(1)
- java 面向对象三大特性(封装,继承,多态)以及抽象、接口的介绍
- 一个基于vue功能强大的表格组件--vxe-table的二次封装
- Hibernate 与mybatis的区别
- 头歌--Java面向对象 - 封装、继承和多态的综合练习
- axios的封装
- SSH三大框架的搭建整合(struts2+spring+hibernate)(转)
- websocket 使用 spring 的service层 ,进而调用里面的 dao层 来操作数据库 ,包括redis、mysql等通用