hibernate---“helloword”程序--优化,标准写法

新建一个HibernateUtil类
用于程序启动时打开hibernate连接。不用每次都要写代码连接。节省系统开支。
package com.test.hibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil(){

}
static {
Configuration cfg= new Configuration();
cfg.configure();
sessionFactory=cfg.buildSessionFactory();

}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
return sessionFactory.openSession();
}
}

改进测试方法(主函数):
package com.test.main;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.test.hibernate.User;
import com.test.hibernateUtil.HibernateUtil;
public class TestHibernate {

/**
* @param args
*/
public static void main(String[] args) {

User user = new User();
try{

user.setName("wqy1");
user.setPassword("1234");

if(addUser(user))
System.out.println("success add user--id="+user.getId()+" name="+user.getName()+" password="+user.getPassword());
}catch(Exception e){
e.printStackTrace();//抛出异常
}


}
public static boolean addUser(User user){
Session session=null;
Transaction ta=null;
boolean result=false;
try{
session = HibernateUtil.getSession();
ta = session.beginTransaction();
session.save(user);
ta.commit();
result=true;
}catch(HibernateException he){
if(ta!=null)
ta.rollback();
throw he;
}finally{
if(session!=null)
session.close();
}
return result;
}
}

好了 完成,这就是一个标准的写法,以后就照这种写法就比较好
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值