<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.pagination</groupId>
<artifactId>paginationInHibernate</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- EHCache uses slf4j for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> My first JSP </title>
</head>
<body>
<form action="pagesrv">
How many entries you want in a page : <input type="text" name="pageNumber" size="20px"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <servlet>
<servlet-name>a</servlet-name>
<servlet-class>com.cv.hibernate.pagination.PaginatonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/pagesrv</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
package com.cv.hibernate.pagination.util;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.cv.hibernate.pagination.model.EmployeeBean;
/**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution. Follows the Thread Local Session pattern, see
* {@link http://hibernate.org/42.html }.
*/
public class HibernateUtil {
private final static Logger logger = Logger.getLogger(HibernateUtil.class);
/**
* Location of hibernate.cfg.xml file. Location should be on the classpath
* as Hibernate uses #resourceAsStream style lookup for its configuration
* file. The default classpath location of the hibernate config file is in
* the default package. Use #setConfigFile() to update the location of the
* configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
// private static String CONFIG_FILE_LOCATION = "hibernate-mysql.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
static {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
public static void saveOrUpdate() {
Session ses = getSession();
for (int i = 100; i < 110; i++) {
EmployeeBean eb = new EmployeeBean();
eb.setId(new Long(i));
eb.setFirstName("chandra");
eb.setLastName("vardhan");
eb.setEmail("meetkodam@gmail.com");
ses.beginTransaction();
ses.saveOrUpdate(eb);
ses.getTransaction().commit();
}
logger.info("Saved successful...");
ses.close();
}
}
package com.cv.hibernate.pagination.model;
/**
* @author Chandra Vardhan
*/
public class EmployeeBean {
private long id;
private String firstName;
private String lastName;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.cv.hibernate.pagination;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.pagination.model.EmployeeBean;
import com.cv.hibernate.pagination.util.HibernateUtil;
/**
* @author Chandra Vardhan
*/
public class PaginatonServlet extends HttpServlet {
Session ses = null;
int initval;
int totrec = 0;
private int pageNumber;
public void init() {
try {
HibernateUtil.saveOrUpdate();
ses = HibernateUtil.getSession();
Query q1 = ses.createQuery("select eb from EmployeeBean eb ");
List l1 = q1.list();
totrec = l1.size();
System.out.print("tot records======" + totrec);
} catch (Exception e) {
e.printStackTrace();
}
}// init
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String parameter = req.getParameter("pageNumber");
try {
pageNumber = Integer.parseInt(parameter);
} catch (Exception n) {
pw.println("Please enter text field as number!!!");
}
HttpSession session = req.getSession();
if (session.getAttribute("counter") == null) {
initval = 0;
session.setAttribute("counter", new Integer(initval));
} else {
Integer i1 = (Integer) session.getAttribute("counter");
initval = i1.intValue() + pageNumber;
session.setAttribute("counter", new Integer(initval));
}
Query q2 = ses.createQuery("select eb from EmployeeBean eb ");
q2.setFirstResult(initval);
q2.setMaxResults(pageNumber);
List l2 = q2.list();
pw.print("<table border='1'><tr><th>No</th><th>Firstname</th><th>Lastname</th><th>Email</th></tr>");
for (int i = 0; i < l2.size(); ++i) {
EmployeeBean eb = (EmployeeBean) l2.get(i);
pw.print("<tr><td>" + eb.getId() + "</td><td>" + eb.getFirstName() + "</td><td>" + eb.getLastName()
+ "</td><td>" + eb.getEmail() + "</td></tr>");
}
pw.print("</table><br>");
if ((initval + pageNumber) < totrec) {
pw.print("<a href='pagesrv?pageNumber="+pageNumber+"'>next</a>");
} else {
pw.print("<a href='index.jsp'>home</a>");
session.invalidate();
}
pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void destroy() {
try {
ses.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, file
# Redirect log messages to console
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.out
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\logs\\hibernate-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-mm-dd HH:mm:ss} %-5p [%c] %m%n
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="show_sql">true</property>
<property name="connection.autocommit">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="format_sql">true</property>
<mapping resource="EmployeeBean.hbm.xml" />
</session-factory>
</hibernate-configuration>
package com.cv.hibernate.proxool;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.logicalcobwebs.proxool.ProxoolFacade;
import com.cv.hibernate.proxool.model.EmployeeBean;
import com.cv.hibernate.proxool.util.HibernateUtil;
public class ProxoolTest {
private final static Logger logger = Logger.getLogger(ProxoolTest.class);
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
EmployeeBean eb = new EmployeeBean();
eb.setId(101);
eb.setFirstName("chandra");
eb.setLastName("vardhan");
eb.setEmail("meetkodam@gmail.com");
session.beginTransaction();
session.saveOrUpdate(eb);
session.getTransaction().commit();
logger.info("Saved successfully...");
HibernateUtil.closeSession();
ProxoolFacade pf = new ProxoolFacade();
pf.shutdown(1);
}
}<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.pagination</groupId>
<artifactId>paginationInHibernate</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- EHCache uses slf4j for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Click here to download eclipse supported ZIP file in hibernate4+Maven+Log4j+PostgreSQL
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.pagination</groupId>
<artifactId>paginationInHibernate</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- EHCache uses slf4j for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> My first JSP </title>
</head>
<body>
<form action="pagesrv">
How many entries you want in a page : <input type="text" name="pageNumber" size="20px"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <servlet>
<servlet-name>a</servlet-name>
<servlet-class>com.cv.hibernate.pagination.PaginatonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/pagesrv</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
package com.cv.hibernate.pagination.util;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.cv.hibernate.pagination.model.EmployeeBean;
/**
* Configures and provides access to Hibernate sessions, tied to the current
* thread of execution. Follows the Thread Local Session pattern, see
* {@link http://hibernate.org/42.html }.
*/
public class HibernateUtil {
private final static Logger logger = Logger.getLogger(HibernateUtil.class);
/**
* Location of hibernate.cfg.xml file. Location should be on the classpath
* as Hibernate uses #resourceAsStream style lookup for its configuration
* file. The default classpath location of the hibernate config file is in
* the default package. Use #setConfigFile() to update the location of the
* configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
// private static String CONFIG_FILE_LOCATION = "hibernate-mysql.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static SessionFactory sessionFactory;
static {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration = configuration.configure(CONFIG_FILE_LOCATION);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
logger.info("%%%% Connection successful %%%%");
} catch (Exception e) {
logger.error("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
public static void saveOrUpdate() {
Session ses = getSession();
for (int i = 100; i < 110; i++) {
EmployeeBean eb = new EmployeeBean();
eb.setId(new Long(i));
eb.setFirstName("chandra");
eb.setLastName("vardhan");
eb.setEmail("meetkodam@gmail.com");
ses.beginTransaction();
ses.saveOrUpdate(eb);
ses.getTransaction().commit();
}
logger.info("Saved successful...");
ses.close();
}
}
package com.cv.hibernate.pagination.model;
/**
* @author Chandra Vardhan
*/
public class EmployeeBean {
private long id;
private String firstName;
private String lastName;
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.cv.hibernate.pagination;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.pagination.model.EmployeeBean;
import com.cv.hibernate.pagination.util.HibernateUtil;
/**
* @author Chandra Vardhan
*/
public class PaginatonServlet extends HttpServlet {
Session ses = null;
int initval;
int totrec = 0;
private int pageNumber;
public void init() {
try {
HibernateUtil.saveOrUpdate();
ses = HibernateUtil.getSession();
Query q1 = ses.createQuery("select eb from EmployeeBean eb ");
List l1 = q1.list();
totrec = l1.size();
System.out.print("tot records======" + totrec);
} catch (Exception e) {
e.printStackTrace();
}
}// init
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String parameter = req.getParameter("pageNumber");
try {
pageNumber = Integer.parseInt(parameter);
} catch (Exception n) {
pw.println("Please enter text field as number!!!");
}
HttpSession session = req.getSession();
if (session.getAttribute("counter") == null) {
initval = 0;
session.setAttribute("counter", new Integer(initval));
} else {
Integer i1 = (Integer) session.getAttribute("counter");
initval = i1.intValue() + pageNumber;
session.setAttribute("counter", new Integer(initval));
}
Query q2 = ses.createQuery("select eb from EmployeeBean eb ");
q2.setFirstResult(initval);
q2.setMaxResults(pageNumber);
List l2 = q2.list();
pw.print("<table border='1'><tr><th>No</th><th>Firstname</th><th>Lastname</th><th>Email</th></tr>");
for (int i = 0; i < l2.size(); ++i) {
EmployeeBean eb = (EmployeeBean) l2.get(i);
pw.print("<tr><td>" + eb.getId() + "</td><td>" + eb.getFirstName() + "</td><td>" + eb.getLastName()
+ "</td><td>" + eb.getEmail() + "</td></tr>");
}
pw.print("</table><br>");
if ((initval + pageNumber) < totrec) {
pw.print("<a href='pagesrv?pageNumber="+pageNumber+"'>next</a>");
} else {
pw.print("<a href='index.jsp'>home</a>");
session.invalidate();
}
pw.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
public void destroy() {
try {
ses.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, file
# Redirect log messages to console
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.out
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\logs\\hibernate-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-mm-dd HH:mm:ss} %-5p [%c] %m%n
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="show_sql">true</property>
<property name="connection.autocommit">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="format_sql">true</property>
<mapping resource="EmployeeBean.hbm.xml" />
</session-factory>
</hibernate-configuration>
package com.cv.hibernate.proxool;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.logicalcobwebs.proxool.ProxoolFacade;
import com.cv.hibernate.proxool.model.EmployeeBean;
import com.cv.hibernate.proxool.util.HibernateUtil;
public class ProxoolTest {
private final static Logger logger = Logger.getLogger(ProxoolTest.class);
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
EmployeeBean eb = new EmployeeBean();
eb.setId(101);
eb.setFirstName("chandra");
eb.setLastName("vardhan");
eb.setEmail("meetkodam@gmail.com");
session.beginTransaction();
session.saveOrUpdate(eb);
session.getTransaction().commit();
logger.info("Saved successfully...");
HibernateUtil.closeSession();
ProxoolFacade pf = new ProxoolFacade();
pf.shutdown(1);
}
}<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cv.pagination</groupId>
<artifactId>paginationInHibernate</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<artifactId>hibernate-core</artifactId>
<groupId>org.hibernate</groupId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<!-- EHCache uses slf4j for logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Click here to download eclipse supported ZIP file in hibernate4+Maven+Log4j+PostgreSQL
No comments:
Post a Comment