直接开搞
最常用的两个方法,保存和更新数据:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class SessUtils {
/**
* 调用Session类,执行以下过程:save → commit → close.
* @param o 实体类对象
*/
public static void save(Object o){
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sess = sf.openSession();
Transaction transaction = sess.beginTransaction();
sess.save(o);
transaction.commit();
sess.close();
sf.close();
}
/**
* 调用Session类,执行以下过程:update → commit → close.
* @param o 实体类对象
*/
public static void update(Object o) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sess = sf.openSession();
Transaction transaction = sess.beginTransaction();
sess.update(o);
transaction.commit();
sess.close();
sf.close();
}
}
测试一下:
BuMen b = new BuMen();
b.setBuMenMingCheng( "财务" );
SessUtils.save( b );
接下来是其他方法:
常用的在这里了:
保存,可以返回id:
Serializable save(Object o)
删除:
void delete(Object o)
根据主键查询:
Object get(Class type,Serializable id)
根据sql
Query createQuery(String hql)
增删改查都有了。
sess的获取:
(1)getCurrentSession在事物提交或者回滚之后会自动关闭,openSession需要你收到关闭,如果使用openSession没有手动关闭,很有可能会导致连接池益处,导致程序出现异常。
(2)openSession每次创建一个新的session对象而getCurrentSession则使用现有的session对象