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語句塊去掉,不建議).
相關文章
相關標籤/搜索