Hibernate在java中的CRUD
2016-01-02 17:40
375 查看
package cn.itcast.hibernate; import java.io.Serializable; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public final class HibernateUtil { private static SessionFactory sessionFactory; private static ThreadLocal session = new ThreadLocal(); private HibernateUtil() { } static { Configuration cfg = new Configuration(); cfg.configure(); sessionFactory = cfg.buildSessionFactory(); } public static Session getThreadLocalSession() { Session s = (Session) session.get(); if (s == null) { s = getSession(); session.set(s); } return s; } public static void closeSession() { Session s = (Session) session.get(); if (s != null) { s.close(); session.set(null); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Session getSession() { return sessionFactory.openSession(); } public static void add(Object entity) { Session s = null; Transaction tx = null; try { s = HibernateUtil.getSession(); tx = s.beginTransaction(); s.save(entity); tx.commit(); } finally { if (s != null) s.close(); } } public static void update(Object entity) { Session s = null; Transaction tx = null; try { s = HibernateUtil.getSession(); tx = s.beginTransaction(); s.update(entity); tx.commit(); } finally { if (s != null) s.close(); } } public static void delete(Object entity) { Session s = null; Transaction tx = null; try { s = HibernateUtil.getSession(); tx = s.beginTransaction(); s.delete(entity); tx.commit(); } finally { if (s != null) s.close(); } } public static Object get(Class clazz, Serializable id) { Session s = null; try { s = HibernateUtil.getSession(); Object obj = s.get(clazz, id); return obj; } finally { if (s != null) s.close(); } } }
相关文章推荐
- java广度优先遍历
- Java 正则表达式
- 【LWJGL2 WIKI】【基础篇】基础1:显示
- 【LWJGL2 WIKI】翻译文章目录
- javaMail的实现
- SSH答疑解惑系列(一)——spring容器是如何启动的
- eclipse project explorer中的工程都不显示的解决办法
- spring quartz 定时器
- Android Studio 配置 JDK1.8 使用Lambda表达式
- LeetCode 171:Excel Sheet Column Numbert
- Spring之Ioc详解01
- MyEclipse 设置注释
- MyEclipse 设置注释
- MyEclipse 设置注释
- Synchronized关键字--总结于《Java多线程编程核心技术》
- eclipse 很好用的高频快捷键
- javaEE之--------------session的活化与钝化
- [Java开发之路](10)DOM解析XML文档
- Java 动态写轮眼 SharinganJPanel (整理)
- java登陆注册界面参考的资料和代码