`
laodaobazi
  • 浏览: 276994 次
  • 性别: 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 所需要的jar包

    7. **缓存机制**: Hibernate支持一级缓存(Session级别的)和二级缓存(SessionFactory级别的)。一级缓存是默认开启的,可以提高性能;二级缓存可以通过第三方插件如Ehcache实现,可跨Session共享数据。 8. **配置...

    hibernate-Annotation.jar

    同时,Hibernate 4.x和5.x版本还引入了更多的特性,如更完善的缓存机制、更好的性能优化以及对JPA 2.0标准的支持等。 综上所述,Hibernate Annotation使得Java开发者能够更高效地管理数据库操作,减少XML配置,提高...

    hibernate annotation hibernate3

    本篇将深入探讨Hibernate 3版本中的注解使用,帮助开发者理解如何利用注解进行数据持久化,提高开发效率。 一、Hibernate 3简介 Hibernate 3是Hibernate ORM框架的一个重要版本,它引入了许多新特性,如对JPA(Java...

    Hibernate distribution and annotation

    5. **缓存**: Hibernate支持一级缓存(Session级别的缓存)和二级缓存(SessionFactory级别的缓存),可以提高性能并减少数据库负载。 **二、Hibernate Annotations 3.3.4** Hibernate Annotations是Hibernate的一...

    hibernate annotation 中文文档

    《Hibernate Annotation 中文文档》是Java开发者们的重要参考资料,它详细介绍了如何在Hibernate框架中使用注解进行对象关系映射(ORM)。Hibernate是一款强大的开源Java持久化框架,它简化了数据库与Java对象之间的...

    hibernate_annotation_中文帮助文档

    - `@Entity`、`@Id`、`@Column`等是标准的JPA注解,而`@Formula`、`@Cacheable`、`@Filter`等是Hibernate特有的,提供更丰富的功能,如计算属性、缓存策略和动态过滤。 5. **通过XML覆写元数据** 虽然注解是首选...

    hibernate 中文文档 and _annotation.chm

    《Hibernate中文文档与...通过阅读《Hibernate_3.2.0_Reference_zh_CN.chm》和《hibernate_annotation.chm》这两份文档,开发者可以深入了解Hibernate的使用方法,熟练掌握ORM技术,提升Java企业级应用的开发效率。

    Hibernate Annotation 学习笔记

    3. 实体类:例如,创建一个`User`类,使用Hibernate Annotation定义实体属性。`@Entity`标记表明这是一个实体类,`@Id`和`@GeneratedValue(strategy = GenerationType.AUTO)`表示`id`字段是主键,且自动生成。数据库...

    SpringMVC Spring Hibernate 框架整合 Annotation Maven Project

    Hibernate还支持二级缓存和事务管理,提高了性能和数据一致性。 **整合过程** 整合SpringMVC、Spring和Hibernate通常涉及以下几个步骤: 1. **配置pom.xml**:引入所需的库依赖,如Spring、SpringMVC、Hibernate、...

    hibernate _annotation 注解编程

    ### Hibernate Annotation注解编程知识点详解 #### 一、概述与设置环境 - **概述**:Hibernate 是一个流行的 Java 持久层框架,它提供了一种面向对象的方式来处理数据库操作。Hibernate 支持多种元数据定义方式,...

    hibernate annotation api chm文件

    Hibernate Annotation API是Hibernate ORM的一种扩展,允许开发者使用Java注解(Annotations)来定义对象-关系映射。这种API避免了传统的Hibernate XML配置文件,使得ORM配置更加内聚且易于维护。 2. **核心注解**...

    第一个Hibernate with Annotation程式(转)

    这个标题暗示我们将讨论如何在项目中首次引入Hibernate,并使用注解(Annotation)进行配置,这是一种简化传统XML配置的方式。 【描述】:“eclipse工程,博文链接:https://xiangzhengyan.iteye.com/blog/86346” ...

    hibernate-annotation-3.2.1

    7. **缓存**:Hibernate提供了缓存机制,如一级缓存(Session级别的)和二级缓存(SessionFactory级别的),可以通过`@Cacheable`,`@Cache`等注解进行配置。 8. **事务管理**:`@Transactional`注解用于标记一个...

    spring_hibernate_annotation的三种实现

    以下将详细介绍"spring_hibernate_annotation的三种实现"。 1. **基于XML的配置** 在早期的Spring和Hibernate集成中,通常使用XML配置文件来定义Bean和数据源,以及映射信息。Spring的`applicationContext.xml`...

    struts2+spring2+hibernate3 Annotation的整合

    在"Struts2+Spring2+Hibernate3 Annotation的整合"中,主要涉及的知识点包括: 1. **Struts2注解**: Struts2框架允许开发者通过注解来配置Action类和方法,如`@Action`定义Action类,`@Results`定义结果页面,...

    Hibernate的Annotation版Hello world实例

    在这个“Hibernate的Annotation版Hello world实例”中,我们将探讨如何利用Hibernate的注解(Annotation)功能来简化实体类的配置,并实现一个基本的数据操作。 首先,Hibernate注解是自Hibernate 3.2版本开始引入...

    hibernate annotation帮助文档

    ### Hibernate Annotation 帮助文档知识点总结 #### 1. 创建注解项目 - **系统需求**:在开始创建一个支持 Hibernate 注解的项目之前,需要确保满足以下系统需求: - Java 开发环境(例如 JDK 1.8 或更高版本)。...

Global site tag (gtag.js) - Google Analytics