`
laodaobazi
  • 浏览: 272767 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Hibernate 使用 Annotation 7(缓存的使用)

阅读更多

Category.java代码:

package com.jlee07.cache;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 * @author JLee
 * 板块
 */
@Entity
@Table(name="Category")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE ,region="jleeCache")
public class Category {

	private int id ;
	private String name ;
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@Column(name="name")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

 

 

Msg.java代码:

package com.jlee07.cache;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="Msg")
public class Msg {

	private int id ;
	private String cont ;
	private Topic topic ;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@Column(name="cont" , length=500)
	public String getCont() {
		return cont;
	}
	public void setCont(String cont) {
		this.cont = cont;
	}
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="topicId")
	public Topic getTopic() {
		return topic;
	}
	public void setTopic(Topic topic) {
		this.topic = topic;
	}
	
}

 

 

Topic.java代码:

package com.jlee07.cache;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * @author Administrator
 * 主题
 */
@Entity
@Table(name="topic")
@NamedQueries({
	@NamedQuery(name="Topic.selectTopic" , query="from Topic t where t.id = :id ") , 
	@NamedQuery(name="Topic.conditionTopic" , query="from Topic t where t.title like :title ")
})
//hibernate3.3.2尚未支持
//@NamedNativeQueries({
//	@NamedNativeQuery(name="native_sql_page" , query="select * from topic limit 2,5")
//})
public class Topic {
	
	private int id ;
	private String title ;
	private Date createDate ;
	public Date getCreateDate() {
		return createDate;
	}
	
	@Column(name="createDate")
	@Temporal(TemporalType.DATE)
	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}
	private Category category ;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@Column(name="title" , length=32)
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="categoryId")
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	
}

 

 

HibernateCacheTest.java代码:

package com.jlee07.cache;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class HibernateCacheTest {

	private static SessionFactory sf ;
	@BeforeClass
	public static void beforeClass(){
		sf = new AnnotationConfiguration().configure().buildSessionFactory() ;
	}
	
	@AfterClass
	public static void afterClass(){
		sf.close() ;
	}
	
	/**
	 * 使用 session 级缓存
	 */
	@Test
	public void testCache1(){
		Session session = sf.getCurrentSession() ;
		session.beginTransaction() ;
		
		Category category = (Category)session.load(Category.class, 1) ;
		System.out.println(category.getName());
		Category category2 = (Category)session.load(Category.class, 1) ;
		System.out.println(category2.getName());
		
		session.getTransaction().commit() ;
	}

	/**
	 * load 和 iterate 默认使用二级缓存
	 * list 默认往二级缓存加数据,但查询的时候不使用缓存
	 * 如果要query使用二级缓存,需要打开查询缓存
	 * 查询缓存依赖 二级缓存 使用查询缓存需要开启二级缓存
	 */
	@Test
	public void testCache2(){
		Session session = sf.getCurrentSession() ;
		session.beginTransaction() ;
		Category category = (Category)session.load(Category.class, 1) ;
		System.out.println(category.getName());
		session.getTransaction().commit() ;
		
		Session session2 = sf.getCurrentSession() ;
		session2.beginTransaction() ;
		Category category2 = (Category)session2.load(Category.class, 1) ;
		System.out.println(category2.getName());
		session2.getTransaction().commit() ;
		
	}
	
	/**
	 * 使用查询缓存
	 */
	@Test
	public void testQueryCache(){
		Session session = sf.getCurrentSession() ;
		session.beginTransaction() ;
		
		List<Category> categories = (List<Category>)session.createQuery("from Category ")
										.setCacheable(true).list() ;
		List<Category> categories2 = (List<Category>)session.createQuery("from Category ")
										.setCacheable(true).list() ;
		
		session.getTransaction().commit() ;
	}

	@Test
	public void testSchemaExport(){
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
	}
	
}

 

 

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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">100</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>	
		 
         <property name="cache.use_second_level_cache">true</property>
         <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
         <property name="cache.use_query_cache">true</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <property name="format_sql">true</property>
		
        <!-- Drop and re-create the database schema on startup -->
        <!--<property name="hbm2ddl.auto">create</property>-->


	<mapping class="com.jlee07.cache.Category"/>
	<mapping class="com.jlee07.cache.Msg"/>
	<mapping class="com.jlee07.cache.Topic"/>

    </session-factory>

</hibernate-configuration>

 

ehcache.xml文件:

<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
<!--     dui xiang yi chu hou fang zhi de di fang -->
    <diskStore path="java.io.tmpdir"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
<!--        
			mo ren cache de pei zhi 
			maxElementsInMemory : she zhi huan cun zhong zui duo fang zhi duo shao ge dui xiang
			eternal : bu mie de yong yuan sheng cun de(yong yuan bu qing chu huan cun zhong de dui xiang) 
			timeToIdleSeconds : she zhi zui da de xian zhi shi jian
			timeToLiveSeconds : she zhi zui da de sheng cun shi jian(wei le he shu ju ku zuo tong bu )
			overflowToDisk :  yi chu de shi hou fang dao ying pan shang mian qu 
-->
    <defaultCache
        maxElementsInMemory="10000" 
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="1200"
        overflowToDisk="true"
        />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
<!--        zi ding yi cache mo ren de cache shi bi xu de -->
    <cache name="jleeCache"
        maxElementsInMemory="10000" 
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="1200"
        overflowToDisk="true"
        />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
        maxElementsInMemory="1000"
        eternal="true"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"
        /> 

    <!-- Place configuration for your caches following -->

</ehcache>

 

分享到:
评论

相关推荐

    hibernate annotation 中文文档

    2.4.7. 缓存 2.4.8. 过滤器 2.4.9. 查询 3. 通过XML覆写元数据 3.1. 原则 3.1.1. 全局级别的元数据 3.1.2. 实体级别的元数据 3.1.3. 属性级别的元数据 3.1.4. 关联级别的元数据 4. Hibernate验证器 4.1. 约束 4.1.1....

    Hibernate配置EhCache缓存之annotation注解[归类].pdf

    Hibernate配置EhCache缓存之annotation注解[归类].pdf

    hibernate annotation帮助文档

    2.4. Hibernate独有的注解扩展 2.4.1. 实体 2.4.2. 标识符 2.4.3. 属性 2.4.3.1. 访问类型 2.4.3.2. 公式 2.4.3.3. 类型 2.4.3.4. 索引 2.4.3.5. @Parent 2.4.3.6. 生成的属性 2.4.4. 继承 2.4.5. 关于...

    马士兵hibernate学习笔记(原版)

    目录 课程内容 1 HelloWorld 2 Hibernate原理模拟 - 什么是O/R Mapping以及为什么... 4 一级缓存和二级缓存和査询缓存(面试题)(详见hibernate_3000_Hibernate_3KindsOf_Cache) 5 事务并发处理(面试的意义更大)

    Hibernate+中文文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    hibernate3.2中文文档(chm格式)

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    HibernateAPI中文版.chm

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    最全Hibernate 参考文档

    5.4.2. 使用 JDK 5.0 的注解(Annotation) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合...

    Hibernate中文详细学习文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    Hibernate 中文 html 帮助文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) ...

    hibernate 体系结构与配置 参考文档(html)

    使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) ...

    Hibernate_3.2.0_符合Java习惯的关系数据库持久化

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent ...

    Hibernate教程

    6.4.2. 使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. ...

    hibernate3.04中文文档.chm

    6.4.2. 使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. ...

    Hibernate3+中文参考文档

    5.4.2. 使用 JDK 5.0 的注解(Annotation) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) 6.2. 集合映射( Collection mappings ) 6.2.1. 集合外键(Collection foreign keys) 6.2.2. 集合...

    Hibernate参考文档

    5.5.2. 使用 JDK 5.0 的注解(Annotation) 5.6. 数据库生成属性(Generated Properties) 5.7. 辅助数据库对象(Auxiliary Database Objects) 6. 集合类(Collections)映射 6.1. 持久化集合类(Persistent collections) ...

    hibernate 框架详解

    使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. 集合...

    Hibernate3的帮助文档

    6.4.2. 使用 JDK 5.0 的注解(Annotation) 7. 集合类(Collections)映射 7.1. 持久化集合类(Persistent collections) 7.2. 集合映射( Collection mappings ) 7.2.1. 集合外键(Collection foreign keys) 7.2.2. ...

    orm:使用 Annotation 处理器和 Sqlite 的 Android Basic-ORM

    基本ORM 使用 Annotation 处理器和 Sqlite 数据库的Beta Android 数据库助手。 Orm 的行为不像“传统”的 orm 库。 实体不附属于任何类型的“状态”或“会话”。 尽可能简单地执行创建/读取/更新/删除操作,让 Basic...

    框架整合jar包及其它功能包_spring4.2.3+hibernate5.0.2+struts2.3.24

    ehcache二级缓存,c3p0连接池,文件上传,dom4j,mysql数据库驱动,jscharts图表统计图走势,JSTL,struts日历控件包,base64加密,Excel文件生成,...ehcache二级缓存配置文件,,支持annotation注解,支持xml配置等。

Global site tag (gtag.js) - Google Analytics