session的load加载方式demo

    本文主要采用实例展现load加载对象的方式:
    1. BankAccount.java
package com.lxh.transaction5;

import java.io.Serializable;

@SuppressWarnings("serial")
public class BankAccount implements Serializable {

	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;
	}

	// 重写EQUAL方法
	public boolean equals(Object other) {
		if ((this == other))
			return true;
		if ((other == null))
			return false;
		if (!(other instanceof BankAccount))
			return false;
		BankAccount castOther = (BankAccount) other;
		return ((this.getId() == castOther.getId()) || (this.getId() != null
				&& castOther.getId() != null && this.getId().equals(
				castOther.getId())))
				&& ((this.getName() == castOther.getName()) || (this.getName() != null
						&& castOther.getName() != null && this.getName()
						.equals(castOther.getName())))
				&& ((this.getBalance() == castOther.getBalance()));
	}

	// 重写HASHCODE方法
	public int hashCode() {
		int result = 17;
		result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
		result = 37 * result + (getName() == null ? 0 : this.getName().hashCode());
		result = 37 * result + this.getBalance();
		return result;
	}
}
    2. 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.transaction5.BankAccount" table="BankAccount" lazy="true">
		<cache usage="read-write" />
		<id name="id" type="string">
			<column name="id" />
		</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>
    3. BankAccountDao.java
package com.lxh.transaction5;

import java.io.Serializable;

public interface BankAccountDao {
	// 查询用户余额
	public int getUserBalanceById(Serializable id);
}
    4. BankAccountDaoImpl.java
package com.lxh.transaction5;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class BankAccountDaoImpl implements BankAccountDao {
	// 日志
	private final static Logger logger = Logger
			.getLogger(BankAccountDaoImpl.class);
	public static SessionFactory sf = SessionFactoryUtil
			.getConfigurationByXML().buildSessionFactory();

	// 查询用户余额
	public int getUserBalanceById(Serializable id) {
		int balance = 0;
		//
		Session session = sf.openSession();
		session.beginTransaction();
		try {
			// load加载
			BankAccount ba = (BankAccount) session.load(BankAccount.class, id);
			balance = ba.getBalance();
			session.getTransaction().commit();
		} catch (Exception e) {
			logger.error("" + e.getMessage());
			session.getTransaction().rollback();
		} finally {
			if (session != null) {
				if (session.isOpen()) {
					session.close();
				}
			}
		}
		return balance;
	}

}
    5. SessionFactoryUtil.java
package com.lxh.transaction5;

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;
	}
}
    6. 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">test</property>
		<property name="connection.password">test</property>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:tran</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">true</property>
		<!-- 对象与数据库表格映像文件 -->
		<mapping resource="com/lxh/transaction5/BankAccount.hbm.xml" />
	</session-factory>
</hibernate-configuration>
    7. Test.java
package com.lxh.transaction5;

public class Test {

	public static void main(String[] args) {
		BankAccountDao bad = new BankAccountDaoImpl();
		// 查询
		for (int i = 0; i < 5; i++) {   
			System.out.println(bad.getUserBalanceById("20151209163409"));
		}
	}

}
    8. 运行结果以及分析
       数据库表结果

       运行结果

       分析:
       只有在调用实体属性的时候才与数据库交互(此例中缓存没有须要查询的对象),第一次以后就能够从缓存中获取。

    9. 补充说明
        若出现"org.hibernate.LazyInitializationException: could not initialize proxy - no Session  ……"问题:        解决方式:        <1> 将load改为get的方式来获得该对象;        <2> 在表示层来开启咱们的session和关闭session,(本例中能够将finally语句块去掉,不建议).
相关文章
相关标签/搜索