Hibernate Data Source Example

Click here to download eclipse supported ZIP file




 
<?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> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
		hibernate word is optional <property name="connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property> 
		<property name="hibernate.connection.username">kcv</property> <property name="hibernate.connection.password">kcv</property> 
		<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property> 
		<property name="show_sql">true</property> <mapping resource="Employee.hbm.xml"/> 
		</session-factory> -->
   <session-factory>
      <property name="hibernate.current_session_context_class">thread</property>
      <property name="hbm2ddl.auto">create</property>
      <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="format_sql">true</property>
      <property name="use_sql_comments">true</property>
      		<mapping class="com.cv.hibernate.servlet.model.Employee" />
   </session-factory>
</hibernate-configuration>


 

    
package com.cv.hibernate.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jboss.logging.Logger;

import com.cv.hibernate.servlet.model.Employee;

@WebServlet("/GetEmployeeByID")
public class GetEmployeeByID extends HttpServlet {
  private static final long serialVersionUID = 1L;
  
  public final Logger logger = Logger.getLogger(GetEmployeeByID.class);
       
  protected void doGet(HttpServletRequest request, HttpServletResponse responsethrows ServletException, IOException {
    int empId = Integer.parseInt(request.getParameter("empId"));
    logger.info("Request Param empId="+empId);
    
    SessionFactory sessionFactory = (SessionFactoryrequest.getServletContext().getAttribute("SessionFactory");
    
    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();
    Employee emp = (Employeesession.get(Employee.class, empId);
    session.getTransaction().commit();
    PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        if(emp != null){
        out.print("<html><body><h2>Employee Details</h2>");
        out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
        out.print("<th>Employee ID</th>");
        out.print("<th>Employee Name</th>");
        out.print("<th>Employee Role</th>");
        
            out.print("<tr>");
            out.print("<td>" + empId + "</td>");
            out.print("<td>" + emp.getName() "</td>");
            out.print("<td>" + emp.getRole() "</td>");
            out.print("</tr>");
        out.print("</table></body><br/>");
        
        out.print("</html>");
        }else{
          out.print("<html><body><h2>No Employee Found with ID="+empId+"</h2></body></html>");
        }
  }

}


 

    
package com.cv.hibernate.servlet.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.jboss.logging.Logger;

@WebListener
public class HibernateSessionFactoryListener implements ServletContextListener {

  public final Logger logger = Logger.getLogger(HibernateSessionFactoryListener.class);
  
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
      SessionFactory sessionFactory = (SessionFactoryservletContextEvent.getServletContext().getAttribute("SessionFactory");
      if(sessionFactory != null && !sessionFactory.isClosed()){
        logger.info("Closing sessionFactory");
      }
      logger.info("Released Hibernate sessionFactory resource");
    }

    public void contextInitialized(ServletContextEvent servletContextEvent) {
      Configuration configuration = new Configuration();
      configuration.configure("hibernate.cfg.xml");
      logger.info("Hibernate Configuration created successfully");
      
      ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
      logger.info("ServiceRegistry created successfully");
      SessionFactory sessionFactory = configuration
        .buildSessionFactory(serviceRegistry);
      logger.info("SessionFactory created successfully");
      
      servletContextEvent.getServletContext().setAttribute("SessionFactory", sessionFactory);
      logger.info("Hibernate SessionFactory Configured successfully");
    }
  
}


 

    
package com.cv.hibernate.servlet.model;

import java.util.Date;

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 javax.persistence.UniqueConstraint;

@Entity
@Table(name="Employee"
     uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
public class Employee {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  @Column(name="ID", nullable=false, unique=true, length=11)
  private int id;
  
  @Column(name="NAME", length=20, nullable=true)
  private String name;
  
  @Column(name="ROLE", length=20, nullable=true)
  private String role;
  
  @Column(name="insert_time", nullable=true)
  private Date insertTime;
  
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getRole() {
    return role;
  }
  public void setRole(String role) {
    this.role = role;
  }
  public Date getInsertTime() {
    return insertTime;
  }
  public void setInsertTime(Date insertTime) {
    this.insertTime = insertTime;
  }
}







#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# 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:\\servlet-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{1}:%L - %m%n


	
<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.hibernate.servlet</groupId> <artifactId>HibernateDataSource</artifactId> <version>1.0</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <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-war-plugin</artifactId> <version>2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> ${project.artifactId} </build> </project>


No comments:

Post a Comment