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();//操作數據庫
    }

這裏寫圖片描述

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章