关键代码:

<class-cache usage="read-write" class="com.shuoeasy.test.User"/>
<!-- 集合级别的二级缓存,写法:包名.类名.字段名 -->
<collection-cache usage="read-write" collection="com.shuoeasy.test.User.orders"/>
<class-cache usage="read-write" class="com.shuoeasy.test.Orders"/>	

或者代替hibernate.cfg.xml:<collection-cache usage="read-write" collection="com.shuoeasy.test.User.orders"/>

<cache usage="read-write"/>

代码片段:

User.java

package com.shuoeasy.test;

import java.util.HashSet;
import java.util.Set;

public class User {
	private int id;
	private String userName;
	
	private Set<Orders> orders = new HashSet<>();
	
	public User() {
	}
	public User(String userName) {
		super();
		this.userName = userName;
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	public Set<Orders> getOrders() {
		return orders;
	}
	public void setOrders(Set<Orders> orders) {
		this.orders = orders;
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + "]";
	}

	
}

User.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-6-25 14:50:51 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>

	<class name="com.shuoeasy.test.User" table="USER" >
		<id name="id" type="int">
			<column name="ID" />
			<!-- 指定主键的生成方式,native:使用数据库本地方式 -->
			<generator class="native" />
		</id>
		<property name="userName" type="java.lang.String">
			<column name="USERNAME" />
		</property>
		<set name="orders" table="ORDERS" inverse="true" batch-size="100">
			<!-- 
			可以在这里配置缓存,代替hibernate.cfg.xml:<collection-cache usage="read-write" collection="com.shuoeasy.test.User.orders"/>
			 -->
			<cache usage="read-write"/>
			<key column="USER_ID"></key>
			<one-to-many class="com.shuoeasy.test.Orders"/>
		</set> 
	</class>
</hibernate-mapping>

Orders.java:

package com.shuoeasy.test;

public class Orders {
	private int id;
	private User user;
	private String title;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	@Override
	public String toString() {
		return "Order [id=" + id + ", user=" + user + ", title=" + title + "]";
	}
	
	
}

Orders.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-6-25 14:50:51 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping  package="com.shuoeasy.test">
	<class name="Orders" table="Orders">
		<id name="id" type="int">
			<column name="ID" />
			<!-- 指定主键的生成方式,native:使用数据库本地方式 -->
			<generator class="native" />
		</id>
		<property name="title" type="java.lang.String">
			<column name="TITLE" />
		</property>
		
		<many-to-one name="user" class="User" column="USER_ID">
	 	</many-to-one>
		
	</class>
</hibernate-mapping>

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="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">111111</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;useLegacyDatetimeCode=false&amp;serverTimezone=Australia/Melbourne&amp;</property>

		<!-- hibernate 的基本信息 -->
		<!-- hibernate 所使用的数据库方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

		<!-- 执行操作时是否在控制台打印sql -->
		<property name="show_sql">true</property>

		<!-- 是否对sql进行格式化 -->
		<property name="format_sql">true</property>

		<!-- 指定自动生成数据表策略 -->
		<property name="hbm2ddl.auto">update</property>
		
		<!-- 启用二级缓存 -->
		<property name="cache.use_second_level_cache">true</property>
		
		<!-- 配置使用的二级缓存产品 -->
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

		<!-- 指定关联的 .hbm.xml文件 -->
		<mapping resource="com/shuoeasy/test/User.hbm.xml" />
		<mapping resource="com/shuoeasy/test/Orders.hbm.xml" />
		
		<class-cache usage="read-write" class="com.shuoeasy.test.User"/>
		<!-- 集合级别的二级缓存,写法:包名.类名.字段名 -->
		<collection-cache usage="read-write" collection="com.shuoeasy.test.User.orders"/>
		<class-cache usage="read-write" class="com.shuoeasy.test.Orders"/>
		
	</session-factory>
</hibernate-configuration>

AppTest.java:

package com.shuoeasy.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest {
	Session session;
	SessionFactory sf;

	@Before
	public void init() {

		Configuration conf = new Configuration().configure();

		ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();

		sf = conf.buildSessionFactory((org.hibernate.service.ServiceRegistry) sr);

		session = sf.openSession();

		session.beginTransaction();
		System.out.println("init");
	}

	@After
	public void destory() {
		session.getTransaction().commit();

		session.close();

		sf.close();
		System.out.println("dectory");
	}

	/**
	 * 测试是否使用缓存
	 * hibernate.cfg.xml 加速配置<class-cache usage="read-write" class="com.shuoeasy.test.User"/> 
	 * 使用缓之后出现一条sql,不适用会出现两条sql。
	 */
	@Test
	public void testGet(){
		User user1 = (User) session.get(User.class, 1);
		System.out.println(user1);
		System.out.println(user1.getOrders().size());
		System.out.println(user1.getOrders());
		
		session.getTransaction().commit();
		session.close();
		session = sf.openSession();
		session.beginTransaction();
		System.out.println("开始第二次查询");
		
		User user2 = (User) session.get(User.class, 1);
		System.out.println(user2);
		System.out.println(user2.getOrders().size());
		System.out.println(user2.getOrders());
		
	}
	
}


你可能感兴趣的文章