Home  >  Hibernate

Enable Second level Cache in Hibernate Annotation

By Arvind Rai, January 29, 2013
In hibernate first level cache is provided by default. Hibernate do that by session. But second level cache can be enabled explicitly. Second level Caching in Hibernate can be done at three labels.

Enable Hibernate Second Level Cache Globally

We need to set a property in our persistence configuration file. The property is hibernate.cache.default_cache_concurrency_strategy. By setting this property, all tables can be cached at second level.


Enable Hibernate Second Level Cache at Table Level by Annotation

In Hibernate Annotation, we use @Cache to set table level cache. We also need to set @Cacheable. The class CacheConcurrencyStrategy of the package org.hibernate.annotations, provides the caching.
@Entity
@Table(name="college")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class College implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="college_id")
    private int collegeId;	
	
	@Column(name="name")
	private String collegeName;
	
	@ElementCollection
	@CollectionTable(name="student", joinColumns=@JoinColumn(name="college_id"))
	@Column(name="student_name")
	private Set<String> students;
	 
	public College(int collegeId,String collegeName){
		this.collegeId=collegeId;
		this.collegeName=collegeName;
	}
	
	public Set<String> getStudents() {
		return students;
	}

	public void setStudents(Set<String> students) {
		this.students = students;
	}

	public int getCollegeId() {
		return collegeId;
	}

	public void setCollegeId(int collegeId) {
		this.collegeId = collegeId;
	}

	public String getCollegeName() {
		return collegeName;
	}

	public void setCollegeName(String collegeName) {
		this.collegeName = collegeName;
	}
}

 

Enable Hibernate Second Level Cache at Column Level by Annotation

In Hibernate Collections to cache the collection at column level @Cache is used and CacheConcurrencyStrategy class provides the caching. We need to set it at property level in our entity.
       @ElementCollection
	@CollectionTable(name="student", joinColumns=@JoinColumn(name="college_id"))
	@Column(name="student_name")
	@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
	private Set<String> students;
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us