hibernate二级缓存学习demo

    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>
hibernate二级缓存学习demo_第1张图片

       2. 不使用二级缓存
<property name="hibernate.cache.use_second_level_cache">false</property>
hibernate二级缓存学习demo_第2张图片

    9. 结果分析
       通过分析可以发现:未使用二级缓存时,查询了2次数据库(执行一次SQL代表查询一次数据库); 使用二级缓存时,只有第1次查询了数据库,第2次为未查询数据库但也能得到相应的结果-----应用了"二级缓存"。

你可能感兴趣的:(hibernate二级缓存学习demo)