hibernate基础2:封装hibernateUtil,实现CRUD
2021-02-20 10:19
标签:文件 standard 配置文件 cer 读取 rac 操作 tst vat 1、封装hibernateUtil 2、实现hibernate新增数据(save) 3、实现hibernate修改数据(save) 4、实现hibernate删除数据(delete) hibernate基础2:封装hibernateUtil,实现CRUD 标签:文件 standard 配置文件 cer 读取 rac 操作 tst vat 原文地址:https://www.cnblogs.com/chai-blogs/p/12919776.htmlpackage com.project.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Configuration cfg = null;
private static StandardServiceRegistry registry = null;
private static SessionFactory factory = null;
private static ThreadLocal
private static void inset() {
Session session = null;
Transaction ts = null;
try {
//创建session
session = HibernateUtil.getSession();
//获取事务并开启事务
ts = session.beginTransaction();
//新增数据
User u = new User();
u.setName("李四");
u.setAge(45);
//保存
session.save(u);
ts.commit();
} catch (Exception e) {
e.printStackTrace();
if(ts!=null)ts.rollback();
}finally {
HibernateUtil.closeSession();
}
}
private static void update() {
Session session = null;
Transaction ts = null;
try {
//创建session
session = HibernateUtil.getSession();
//获取事务并开启事务
ts = session.beginTransaction();
//查询数据
User u = (User) session.get(User.class, 2);
//修改数据
u.setName("小李子");
//保存
session.save(u);
ts.commit();
} catch (Exception e) {
e.printStackTrace();
if(ts!=null)ts.rollback();
}finally {
HibernateUtil.closeSession();
}
}private static void delete() {
Session session = null;
Transaction ts = null;
try {
//创建session
session = HibernateUtil.getSession();
//获取事务并开启事务
ts = session.beginTransaction();
//查询数据
User u = (User) session.get(User.class, 2);
//删除
session.delete(u);
ts.commit();
} catch (Exception e) {
e.printStackTrace();
if(ts!=null)ts.rollback();
}finally {
HibernateUtil.closeSession();
}
}
下一篇:Pointer Networks
文章标题:hibernate基础2:封装hibernateUtil,实现CRUD
文章链接:http://soscw.com/index.php/essay/57938.html