笔记 03_传智播客hibernate教程_hibernate入门案例的代码优化
来源:互联网 发布:三星手机官方软件 编辑:程序博客网 时间:2024/03/29 22:55
domain对象和映射文件没有改变。
ackage ntt.bhb.xxl.two.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
// 将初始化的工作,有工具类完成
// 工具类特点
// 1 不希望被继承 -> final
// 2 不希望存在多个实例 -> 单例模式 or 私有构造函数(工具类使用静态方法)
public final class HibernateUtil {
//这个静态变量应该是 sessionFactory,而不是session
//private static Session session;
//常驻内存的应该是工厂而不是产品
private static SessionFactory sessionFactory;
private HibernateUtil(){
}
static {
Configuration cfg = new Configuration();
// 读取解析hibernate.cfg.xml
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
}
public static Session getSession() {
return sessionFactory.openSession();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package ntt.bhb.xxl.two.test;
import java.util.Date;
import ntt.bhb.xxl.two.domains.User;
import ntt.bhb.xxl.two.util.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.Session;
public class Base {
public static void main(String[] args) {
User user = new User();
user.setBirthday(new Date());
user.setName("sbbaohongbinwoshinibaba");
addUser(user);
}
static void addUser(User user ){
Session session = null;
Transaction transaction = null;
try {
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
session.save(user);
transaction.commit();
} catch (HibernateException e) {
//在使用对象之前,先判断是否为空
if (transaction != null){
transaction.rollback();
}
// 处理不了的异常,继续往上抛
throw e;
// 一定要释放資源 -> finally
}finally{
//在使用对象之前,先判断是否为空
if(session != null){
session.close();
}
}
}
}
- 笔记 03_传智播客hibernate教程_hibernate入门案例的代码优化
- 笔记 02_传智播客hibernate教程_hibernate入门案例的细节分析
- 笔记 01_传智播客hibernate教程_hibernate介绍与动手入门体验
- 03 hibernate入门案例的代码优化(视频笔记)
- Hibernate优化_Hibernate性能优化_Hibernate优化方案(上)
- Hibernate优化_Hibernate性能优化_Hibernate优化方案(下)
- Hibernate优化_Hibernate性能优化_Hibernate优化方案(上)
- 【转载】Hibernate优化_Hibernate性能优化_Hibernate优化方案(下)
- Hibernate优化_Hibernate性能优化_Hibernate优化方案(上)
- Hibernate教程01_Hibernate的HelloWorld及基本配置
- Hibernate教程03_Hibernate核心开发接口介绍
- Hibernate学习之入门案例笔记
- Hebernate之案例代码优化笔记
- 常见对象_在大串中查找小串出现的次数案例代码优化
- 20_Hibernate入门
- Hibernate 总结笔记(2)Hibernate入门案例
- hibernate的入门的一个简单案例
- 【第11篇】最全的中文TypeScript入门指南详解案例教程与代码
- 郁闷啊
- Flash 3D引擎对比
- 浅谈window.attachEvent
- YCbCr-转载自百度
- C++中的预处理命令
- 笔记 03_传智播客hibernate教程_hibernate入门案例的代码优化
- jquery
- 另辟新径 domino 搞博客
- 用 C# 编写一个停放在任务栏上的图标程序
- PMP培训后的感悟分享
- VC6.0使用的18个技巧
- 软件测试之中文网络资源总汇
- vc6.0 注释多行代码
- 关于双路由