1. hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 數據庫連接配置 -->
<property name="connection.username">UPCFJ</property>
<property name="connection.password">UPCFJ</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@192.168.21.15:1521:UPCDB</property>
<!-- SQL方言 -->
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<!-- 自動建立數據表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 顯示實際操做數據庫時的SQL -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">false</property>
<!-- 編碼方式 -->
<property name="connection.characterEncoding">UTF-8</property>
<!-- 事務相關 -->
<property name="current_session_context_class">thread</property>
<property name="connection.release_mode">auto</property>
<property name="transaction.auto_close_session">false</property>
<property name="connection.autocommit">false</property>
<!-- C3P0數據源設置 -->
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">20</property>
<property name="c3p0.timeout">1800</property>
<property name="c3p0.max_statements">50</property>
<!-- 查詢緩存 -->
<!-- <property name="hibernate.cache.use_query_cache">true</property> -->
<!-- 二級緩存 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<!-- 對象與數據庫表格映像文件 -->
<mapping resource="com/lxh/transaction4/BankAccount.hbm.xml" />
</session-factory>
</hibernate-configuration>
2. BankAccount.java
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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.lxh.transaction4.BankAccount" table="BankAccount">
<cache usage="read-write" />
<id name="id" type="string">
<column name="id" />
<!-- <generator class="assigned"></generator> -->
</id>
<!-- name字段設置惟一約束 -->
<property name="name" type="string" unique-key="true">
<column name="name" not-null="true" />
</property>
<property name="balance" type="java.lang.Integer">
<column name="balance" />
</property>
</class>
</hibernate-mapping>
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 + "'");
// List<BankAccount> list = 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<BankAccount> 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;
}
}
6. SessionFactoryUtil.java
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. 使用二級緩存
<property name="hibernate.cache.use_second_level_cache">true</property>
2. 不使用二級緩存
<property name="hibernate.cache.use_second_level_cache">false</property>

9. 結果分析 經過分析能夠發現:未使用二級緩存時,查詢了2次數據庫(執行一次SQL表明查詢一次數據庫); 使用二級緩存時,只有第1次查詢了數據庫,第2次爲未查詢數據庫但也能獲得相應的結果-----應用了"二級緩存"。