Hibernate 转账功能 (事务处理)

A转100块给B (简单操作) 
数据库的操作思路:

首先A的总金额减100,让后B的总金额加100。
  •  

事务处理:

如果在转账的过程中出现断电等情况不能一次性完成这个操作,则会出现加减操作不同步,导致转账功能不能正常实现。

多用户问题:

每用一次openSession,服务器都会new一个新的session空间,这样的话会严重占用系统空间,影响系统个性能。

解决办法:

运用本地线程,实现一个session空间可以多次利用
  •  

在这里Hibernate基本配置文件和UserBean配置文件就不做介绍了

代码演示里主要用到的配置文件有: 
hibernate.cfg.xml 
User.hbm.xml 
log4j2.xml

//HibernateUtil  工具类  代码编写
    //加载配置文件
    private static Configuration cfg = new Configuration().configure();
    //session工厂创建
    private static SessionFactory sf = cfg.buildSessionFactory();
    //创建本地线程
    private static ThreadLocal<Session> t = new ThreadLocal<Session>();
    //日志文件
    private static Logger log = LogManager.getLogger("HibernateUtil.class");//注意是导入apache.logging包
    //操作数据库的session工具类获取
    //打开session
    public static Session openSession(){
        log.info("获取session工具!");
        return sf.openSession();
    }
    //事务回滚
    public static void rollBack(Transaction t){
        log.info("事务回滚!");
            t.rollback();
    }
    //关闭session
    public static void closeSession(Session session){
        log.info("关闭session!");
        session.close();
    }
    //创建本地线程,减少系统负担
    public static Session getSession(){
        log.info("获取session工具!");
        Session s = t.get();
        if(s==null){//判断session空间是否存在,如果不存在就new一个
            Session temp = sf.openSession();
            t.set(temp);
        }
        return t.get();
    }
//运用hibernate 中的getCurrentSession
public static Session getCurrentSessionx(){
log.info("获取hibernate getCurrentSession工具,需在核心配置加上thread配置,需管理事务才能使用!");
return sf.getCurrentSession();
}
//service 代码编写
public void zhuanzhang() {
        Session session = HibernateUtil.getSession();//本地线程
        Transaction t = null;
        DaoDemo3 dao = new DaoDemo3();
        try {
            t = session.beginTransaction();//开始事务处理
            dao.updateMoney(1, -100);//转账操作
//          int i = 1/0 ; //人造断电,发生错误
            dao.updateMoney(2, 100);//转账操作
            t.commit();//提交事务
        } catch (Exception e) {
            HibernateUtil.rollBack(t);//事务回滚
            e.printStackTrace();
        } finally {
            HibernateUtil.closeSession(session);//关闭session
        }
    }
//dao 代码编写
    public void updateMoney(Integer id, double money) {
        String hql = "update User set money = money +? where Id = ? ";
        Query q = HibernateUtil.getSession().createQuery(hql);
        q.setParameter(0, money);
        q.setParameter(1, id);
        q.executeUpdate();//操作数据库
    }

猜你喜欢

转载自blog.csdn.net/qqmlxy1/article/details/82765035