2. BankAccount.javaUPCFJ UPCFJ oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@192.168.21.15:1521:UPCDB org.hibernate.dialect.OracleDialect update true true false UTF-8 thread auto false false 5 20 1800 50 org.hibernate.cache.EhCacheProvider false
package com.lxh.transaction4;import java.io.Serializable;public class BankAccount implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String id; private String name; private int balance; public BankAccount(){ } public BankAccount(String id, String name, int balance) { this.id = id; this.name = name; this.balance = balance; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; }}3. BankAccount.hbm.xml
4. BankAccountDao.java
package com.lxh.transaction4;public interface BankAccountDao { // 添加账户 public void addUser(BankAccount ba); // 查询账户----判断账户是否存在 public BankAccount getUserById(String id); // 删除账户 public void deleteUserById(String Id); // 更新账户 public boolean updateUserById(String id,String changeName); // 转账 public boolean transferAccont(String fromAccountName,String toAccountName,int tradeMoney);}5. BankAccountDaoImpl.java
package com.lxh.transaction4;import java.util.List;import org.apache.log4j.Logger;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class BankAccountDaoImpl implements BankAccountDao { // 日志 private final static Logger logger = Logger .getLogger(BankAccountDaoImpl.class); public static SessionFactory sf = SessionFactoryUtil .getConfigurationByXML().buildSessionFactory(); // 添加账户 @Override public void addUser(BankAccount ba) { // Session session = sf.openSession(); session.beginTransaction(); // save try { session.save(ba); session.getTransaction().commit(); } catch (Exception e) { logger.error("保存用户信息失败:\t" + e.getMessage()); session.getTransaction().rollback(); } finally { if (session != null) { if (session.isOpen()) { session.close(); } } } } // 删除账户 public void deleteUserById(String id) { Session session = sf.openSession(); session.beginTransaction(); try { session.delete(this.getUserById(id)); // 删除成功,提交事务 session.getTransaction().commit(); } catch (Exception e) { logger.error("删除账户失败:\t" + e.getMessage()); // 删除失败,回滚 session.getTransaction().rollback(); } finally { if (session != null) { if (session.isOpen()) { session.close(); } } } } // 更新账户 public boolean updateUserById(String id, String changeName) { // flag boolean flag = false; // Session session = sf.openSession(); session.beginTransaction(); try { // BankAccount ba = this.getUserById(id); ba.setName(changeName); session.update(ba); session.getTransaction().commit(); } catch (Exception e) { logger.error("更新账户失败:\t" + e.getMessage()); session.getTransaction().rollback(); } finally { if (session != null) { if (session.isOpen()) { session.close(); } } } // return flag; } // 查询用户 public BankAccount getUserById(String id) { BankAccount ba = null; // //Session session = sf.openSession(); Session session = sf.getCurrentSession(); // 当前session session.beginTransaction(); try { // 方式一 // Query q = session.createQuery("from BankAccount ba where ba.id='" // + id + "'"); // List6. SessionFactoryUtil.javalist = q.list(); // if (list != null && 0 != list.size()) { // ba = list.get(0); // } // 方式二 ba = (BankAccount) session.get(BankAccount.class, id); // 方式三 // ba = (BankAccount) session.load(BankAccount.class, id); } catch (Exception e) { logger.error("" + e.getMessage()); } finally { if (session != null) { if (session.isOpen()) { session.close(); } } } return ba; } // 查询用户 @SuppressWarnings("unchecked") public BankAccount getUserByName(String name) { BankAccount ba = null; // Session session = sf.openSession(); session.beginTransaction(); Query q = session.createQuery("from BankAccount ba where ba.name='" + name + "'"); try { List list = q.list(); if (list != null && 0 != list.size()) { ba = list.get(0); } } catch (Exception e) { logger.error("" + e.getMessage()); } finally { if (session != null) { if (session.isOpen()) { session.close(); } } } return ba; } // 转账 public boolean transferAccont(String fromAccountName, String toAccountName, int tradeMoney) { // 转账标识 boolean flag = true; // 判断对方账户是否存在 BankAccount toAcc = this.getUserByName(toAccountName); if (null == toAcc) { // 对方账户不存在 flag = false; logger.info("对方账户:" + toAccountName + ",不存在,请核查后转账。"); } else { // 获取并开启事务 Configuration conf = SessionFactoryUtil.getConfigurationByXML(); SessionFactory sf = conf.buildSessionFactory(); Session session = sf.openSession(); Transaction tran = session.beginTransaction(); tran.begin(); // 执行SQL语句 BankAccount fromAcc = this.getUserByName(fromAccountName); if (null == fromAcc) { // 对方账户不存在 flag = false; logger.info("转账账户:" + fromAccountName + ",不存在,请核查后转账。"); } else { /** * 对方账户存在,判断余额是否满足转账金额 */ if (tradeMoney <= fromAcc.getBalance()) { /** * 小于交易金额,允许转账 */ // 设置转账方和被转账方的金额 fromAcc.setBalance(fromAcc.getBalance() - tradeMoney); toAcc.setBalance(toAcc.getBalance() + tradeMoney); System.out.println(fromAcc + "," + toAcc); // 执行更新操作 session.update(fromAcc); session.update(toAcc); tran.commit(); } else { // 转出方余额小于交易金额,不允许转账 flag = false; logger.info("您的余额【" + fromAcc.getBalance() + "】小于转账金额【" + tradeMoney + "】,不能转账。"); tran.rollback(); } } // 关闭 if (session != null) { if (session.isOpen()) { // session.clear(); session.close(); } } } // 返回 return flag; }}
package com.lxh.transaction4;import java.io.File;import org.hibernate.cfg.Configuration;public class SessionFactoryUtil { // path private static String path = SessionFactoryUtil.class.getResource("") .getPath().toString(); // hibernate.cfg.xml文件方式获取 public static Configuration getConfigurationByXML() { // 加载配置文件 Configuration config = new Configuration(); Configuration cfg = config.configure(new File(path + "hibernate.cfg.xml")); return cfg; }}7. Test.java
package com.lxh.transaction4;public class Test { public static void main(String[] args) { BankAccountDao bad = new BankAccountDaoImpl(); // 查询 for (int i = 0; i < 2; i++) { System.out.println(Thread.currentThread().getId() + ":\t" + bad.getUserById("20151209163409")); } }}8. 运行结果 1. 使用二级缓存
2. 不使用二级缓存true
9. 结果分析 通过分析可以发现:未使用二级缓存时,查询了2次数据库(执行一次SQL代表查询一次数据库); 使用二级缓存时,只有第1次查询了数据库,第2次为未查询数据库但也能得到相应的结果-----应用了"二级缓存"。false