jpa second level cache

Posted: April 14, 2012 in Hibernate

Hibernate3 – JPA Annotations (Second Level Cache)

Here I used technologies are hibernate3, JPA, Servlet, Eclipse Helios (IDE)

Project Structure:

Hibernate-JPA-SecondLevelCache

src

com.shal.controller

| —>  MyController.java

com.shal.model

|—> Product.java

com.shal.util

|—>HibernateUtil.java

META-INF

|—>persistence.xml

hibernate.cfg.xml

ehcache.xml

WebContent

Index.jsp

WEB-INF

|—> web.xml

lib

|—> ehcache-1.2.3.jar (rest of the jar’s u hv seen in my previous one)

1)        Create a table in database named as products

CREATE TABLE `products` (

`pid` int(4) NOT NULL AUTO_INCREMENT,

`pname` varchar(25) DEFAULT NULL,

`price` double DEFAULT NULL,

PRIMARY KEY (`pid`)

) ENGINE=InnoDB AUTO_INCREMENT=107 DEFAULT CHARSET=latin1

Insert values into products(1,”gopal”,5000)

Insert values into products(2,”satya”,6000)

2)       MyController.java (Servlet)

package com.shal.controller;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import org.hibernate.criterion.Restrictions;

import com.shal.model.Product;

import com.shal.util.HibernateUtil;

public class MyController extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

Session session =HibernateUtil.getSessionFactory().openSession();

session.beginTransaction().begin();

try{

int no = Integer.parseInt(req.getParameter(“productId”));

Product  product=(Product)session.createCriteria(Product.class)

.add(Restrictions.eq(“pid”,no))

.setCacheable(true)

.uniqueResult();

System.out.println(“Name “+product.getPname()+”Price

“+product.getPrice());

}

catch (Exception e) {

// TODO: handle exception

session.beginTransaction().rollback();

e.printStackTrace();

}

finally{

session.close();

}}}

3)  Product.java

package com.shal.model;

import java.io.Serializable;

import javax.persistence.*;

import org.hibernate.annotations.Cache;

import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity

@Table(name=”products”)

@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

public class Product implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@Column(unique=true, nullable=false)

private int pid;

@Column(length=25)

private String pname;

private double price;

public Product() {

}

//setters and getters for all fields

}

4)       HibernateUtil.java

package com.shal.util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory()

{

try {

// Create the SessionFactory from hibernate.cfg.xml

return new AnnotationConfiguration().configure().buildSessionFactory();

} catch (Throwable ex) {

System.err.println(“Initial SessionFactory creation failed.” + ex);

throw new ExceptionInInitializerError(ex);

}                }

public static SessionFactory getSessionFactory() {

return sessionFactory;

}}

5)       persistence.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<persistence version=”2.0″ xmlns=”http://java.sun.com/xml/ns/persistence&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd”&gt;

<persistence-unit name=”Hibernate-JPA-SecondLevelCache”>

<class>com.shal.model.Product</class>

</persistence-unit>

</persistence>

6)       ehcache.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<ehcache>

<defaultCache maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”120″ timeToLiveSeconds=”200″ />

<cache name=”com.shal.model.Product” maxElementsInMemory=”100″ eternal=”false” timeToIdleSeconds=”200″ timeToLiveSeconds=”200″ />

</ehcache>

 7)       hibernate.cfg.xml

<hibernate-configuration>

<session-factory>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”connection.url”>jdbc:mysql://localhost/gopal</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>shal</property>

<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>

<property name=”cache.provider_class”>org.hibernate.cache.EhCacheProvider</property>

<property name=”cache.use_query_cache”>true</property>

<property name=”cache.use_second_level_cache”>true</property>

<property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>

<property name=”show_sql”>true</property>

<property name=”hbm2ddl.auto”>update</property>

<mapping class=”com.shal.model.Product”></mapping>

</session-factory>

</hibernate-configuration>

8)       web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; id=”WebApp_ID” version=”2.5″>

<display-name>Hibernate-JPA-SecondLevelCache</display-name>

<servlet>

<servlet-name>dopost</servlet-name>

<servlet-class>com.shal.controller.MyController</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>dopost</servlet-name>

<url-pattern>/dopost</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

9)       index.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″

pageEncoding=”ISO-8859-1″%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”&gt;

<html><head/>

<body>

<form action=”dopost” method=”post”>

<center>

Enter Product Number:

<input type=”text” name=”productId”></input>

<input type=”submit” value=”send”></input>

</center>

</form>

</body>

</html>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s