Spring Hibernate Example

Click here to download eclipse supported ZIP file



This is allemployees.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>University Enrollments</title>
<style>
tr:first-child{
font-weight: bold;
background-color: #C6C9C4;
}
</style>
</head>
<body>
<h2>List of Employees</h2>
<table border="1">
<tr>
<td>NAME</td><td>Joining Date</td><td>Salary</td><td>SSN</td><td>Delete</td>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td>${employee.name}</td>
<td>${employee.joiningDate}</td>
<td>${employee.salary}</td>
<td><a href="<c:url value='/edit-${employee.ssn}-employee' />">${employee.ssn}</a></td>
<td><a href="<c:url value='/delete-${employee.ssn}-employee' />">delete</a></td>
</tr>
</c:forEach>
</table>
<br/>
<a href="<c:url value='/new' />">Add New Employee</a>
</body>
</html>


This is registration.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="runnable.css" />
<style>
h1 {
font-family: Helvetica;
font-weight: 100; }
body {
color: #333;
text-align: center; }
</style>
</head>
<body>
<script language="javascript">
$(document).ready(
function() {
$("#datepicker").datepicker({
changeMonth : true,
changeYear : true
});

}
);
</script>
<h2>Registration Form</h2>
<form:form method="POST" modelAttribute="employee">
<form:input type="hidden" path="id" id="id" />
<table align="center">
<tr>
<td><label for="name">Name: </label></td>
<td><form:input path="name" id="name" /></td>
<td><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td><label for="joiningDate">Joining Date: </label></td>
<td><form:input path="joiningDate" id="datepicker" /></td>
<td><form:errors path="joiningDate" cssClass="error" /></td>
</tr>
<tr>
<td><label for="salary">Salary: </label></td>
<td><form:input path="salary" id="salary" /></td>
<td><form:errors path="salary" cssClass="error" /></td>
</tr>
<tr>
<td><label for="ssn">SSN: </label></td>
<td><form:input path="ssn" id="ssn" /></td>
<td><form:errors path="ssn" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><c:choose>
<c:when test="${edit}">
<input type="submit" value="Update" />
</c:when>
<c:otherwise>
<input type="submit" value="Register" />
</c:otherwise>
</c:choose></td>
</tr>
</table>
</form:form>
<br />
<br /> Go back to
<a href="<c:url value='/list' />">List of All Employees</a>
</body>
</html>


This is success.jsp JSP file and it is used display the output for the application.



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Confirmation Page</title>
</head>
<body>
message : ${success}
<br/>
<br/>
Go back to <a href="<c:url value='/list' />">List of All Employees</a>
</body>
</html>



This is AppConfig.java file having the source code to execute business logic.


 

    
package com.cv.spring.mvc.configuration;

import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
 @author Chandra Vardhan
 */
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.cv.spring.mvc")
public class AppConfig {
  
  private final static Logger LOGGER = Logger.getLogger(AppConfig.class);
  
  @Bean
  public ViewResolver viewResolver() {
    LOGGER.info("IN AppConfig.viewResolver()");
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    LOGGER.info("OUT AppConfig.viewResolver()");
    return viewResolver;
  }
  
  @Bean
  public MessageSource messageSource() {
    LOGGER.info("IN AppConfig.messageSource()");
      ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
      messageSource.setBasename("messages");
      LOGGER.info("OUT AppConfig.messageSource()");
      return messageSource;
  }
}


This is AppInitializer.java file having the source code to execute business logic.


 

    
package com.cv.spring.mvc.configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.apache.log4j.Logger;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
 @author Chandra Vardhan
 */
public class AppInitializer implements WebApplicationInitializer {
  
  private final static Logger LOGGER = Logger.getLogger(AppInitializer.class);
  
  public void onStartup(ServletContext containerthrows ServletException {
    LOGGER.info("IN AppInitializer.onStartup(-)");
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(AppConfig.class);
    ctx.setServletContext(container);

    ServletRegistration.Dynamic servlet = container.addServlet(
        "dispatcher"new DispatcherServlet(ctx));

    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
    LOGGER.info("OUT AppInitializer.onStartup(-)");
  }

}


This is HibernateConfiguration.java file having the source code to execute business logic.


 

    
package com.cv.spring.mvc.configuration;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 @author Chandra Vardhan
 */
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.cv.spring.mvc" })
@PropertySource(value = "classpath:application.properties" })
public class HibernateConfiguration {

  private final static Logger LOGGER = Logger
      .getLogger(HibernateConfiguration.class);

  @Autowired
  private Environment environment;

  @Bean
  public LocalSessionFactoryBean sessionFactory() {
    LOGGER.info("IN HibernateConfiguration.sessionFactory(-)");
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory
        .setPackagesToScan(new String[] { "com.cv.spring.mvc.model" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    LOGGER.info("OUT HibernateConfiguration.sessionFactory(-)");
    return sessionFactory;
  }

  @Bean
  public DataSource dataSource() {
    LOGGER.info("IN HibernateConfiguration.dataSource(-)");
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment
        .getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource
        .setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource
        .setPassword(environment.getRequiredProperty("jdbc.password"));
    LOGGER.info("OUT HibernateConfiguration.dataSource(-)");
    return dataSource;
  }

  private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect",
        environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql",
        environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql",
        environment.getRequiredProperty("hibernate.format_sql"));
    properties.put("hibernate.hbm2ddl.auto",
        environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return properties;
  }

  @Bean
  @Autowired
  public HibernateTransactionManager transactionManager(SessionFactory s) {
    LOGGER.info("IN HibernateConfiguration.transactionManager(-)");
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(s);
    LOGGER.info("OUT HibernateConfiguration.transactionManager(-)");
    return txManager;
  }
}


This is AppController.java file having the controller logic and it will have the services defined in it.


 

    
package com.cv.spring.mvc.controller;

import java.util.List;
import java.util.Locale;

import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cv.spring.mvc.model.Employee;
import com.cv.spring.mvc.service.EmployeeService;
/**
 @author Chandra Vardhan
 */
@Controller
@RequestMapping("/")
public class AppController {
  
  private final static Logger LOGGER = Logger.getLogger(AppController.class);

  @Autowired
  EmployeeService service;
  
  @Autowired
  MessageSource messageSource;

  /*
   * This method will list all existing employees.
   */
  @RequestMapping(value = "/""/list" }, method = RequestMethod.GET)
  public String listEmployees(ModelMap model) {
    LOGGER.info("IN AppController.listEmployees(-)")

    List<Employee> employees = service.findAllEmployees();
    model.addAttribute("employees", employees);
    LOGGER.info("OUT AppController.listEmployees(-)")
    return "allemployees";
  }

  /*
   * This method will provide the medium to add a new employee.
   */
  @RequestMapping(value = "/new" }, method = RequestMethod.GET)
  public String newEmployee(ModelMap model) {
    LOGGER.info("IN AppController.newEmployee(-)")
    Employee employee = new Employee();
    model.addAttribute("employee", employee);
    model.addAttribute("edit"false);
    LOGGER.info("OUT AppController.newEmployee(-)")
    return "registration";
  }

  /*
   * This method will be called on form submission, handling POST request for
   * saving employee in database. It also validates the user input
   */
  @RequestMapping(value = "/new" }, method = RequestMethod.POST)
  public String saveEmployee(@Valid Employee employee, BindingResult result,
      ModelMap model) {
    LOGGER.info("IN AppController.saveEmployee(- - -)")
    if (result.hasErrors()) {
      return "registration";
    }

    /*
     * Preferred way to achieve uniqueness of field [ssn] should be implementing custom @Unique annotation 
     * and applying it on field [ssn] of Model class [Employee].
     
     * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
     * framework as well while still using internationalized messages.
     
     */
    if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
      FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn"new String[]{employee.getSsn()}, Locale.getDefault()));
        result.addError(ssnError);
      return "registration";
    }    
    service.saveEmployee(employee);
    model.addAttribute("success""Employee " + employee.getName() " registered successfully");
    LOGGER.info("IN AppController.saveEmployee(- - -)")
    return "success";
  }


  /*
   * This method will provide the medium to update an existing employee.
   */
  @RequestMapping(value = "/edit-{ssn}-employee" }, method = RequestMethod.GET)
  public String editEmployee(@PathVariable String ssn, ModelMap model) {
    LOGGER.info("IN AppController.editEmployee(- -)")
    Employee employee = service.findEmployeeBySsn(ssn);
    model.addAttribute("employee", employee);
    model.addAttribute("edit"true);
    LOGGER.info("OUT AppController.editEmployee(- -)")
    return "registration";
  }
  
  /*
   * This method will be called on form submission, handling POST request for
   * updating employee in database. It also validates the user input
   */
  @RequestMapping(value = "/edit-{ssn}-employee" }, method = RequestMethod.POST)
  public String updateEmployee(@Valid Employee employee, BindingResult result,
      ModelMap model, @PathVariable String ssn) {
    if (result.hasErrors()) {
      return "registration";
    }
    if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
      FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn"new String[]{employee.getSsn()}, Locale.getDefault()));
        result.addError(ssnError);
      return "registration";
    }
    service.updateEmployee(employee);
    model.addAttribute("success""Employee " + employee.getName()  " updated successfully");
    return "success";
  }

  
  /*
   * This method will delete an employee by it's SSN value.
   */
  @RequestMapping(value = "/delete-{ssn}-employee" }, method = RequestMethod.GET)
  public String deleteEmployee(@PathVariable String ssn) {
    service.deleteEmployeeBySsn(ssn);
    return "redirect:/list";
  }

}


This is AbstractDao.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.mvc.dao;

import java.io.Serializable;

import java.lang.reflect.ParameterizedType;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
/**
 @author Chandra Vardhan
 */
public abstract class AbstractDao<PK extends Serializable, T> {
  
  private final Class<T> persistentClass;
  
  @SuppressWarnings("unchecked")
  public AbstractDao(){
    this.persistentClass =(Class<T>) ((ParameterizedTypethis.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
  }
  
  @Autowired
  private SessionFactory sessionFactory;

  protected Session getSession(){
    return sessionFactory.getCurrentSession();
  }

  @SuppressWarnings("unchecked")
  public T getByKey(PK key) {
    return (TgetSession().get(persistentClass, key);
  }

  public void persist(T entity) {
    getSession().persist(entity);
  }

  public void delete(T entity) {
    getSession().delete(entity);
  }
  
  protected Criteria createEntityCriteria(){
    return getSession().createCriteria(persistentClass);
  }

}


This is EmployeeDao.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.mvc.dao;

import java.util.List;

import com.cv.spring.mvc.model.Employee;
/**
 @author Chandra Vardhan
 */
public interface EmployeeDao {

  Employee findById(int id);

  void saveEmployee(Employee employee);
  
  void deleteEmployeeBySsn(String ssn);
  
  List<Employee> findAllEmployees();

  Employee findEmployeeBySsn(String ssn);

}


This is EmployeeDaoImpl.java file having the DAO logic to access the database information.


 

    
package com.cv.spring.mvc.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.cv.spring.mvc.model.Employee;
/**
 @author Chandra Vardhan
 */
@Repository("employeeDao")
public class EmployeeDaoImpl extends AbstractDao<Integer, Employee> implements EmployeeDao {
   private final static Logger LOGGER = Logger.getLogger(EmployeeDaoImpl.class);
    
  public Employee findById(int id) {
    return getByKey(id);
  }

  public void saveEmployee(Employee employee) {
    persist(employee);
  }

  public void deleteEmployeeBySsn(String ssn) {
    LOGGER.info("IN EmployeeDaoImpl.deleteEmployeeBySsn(-)")
    Query query = getSession().createSQLQuery("delete from Employee where ssn = :ssn");
    query.setString("ssn", ssn);
    query.executeUpdate();
    LOGGER.info("IN EmployeeDaoImpl.deleteEmployeeBySsn(-)");
  }

  @SuppressWarnings("unchecked")
  public List<Employee> findAllEmployees() {
    LOGGER.info("IN EmployeeDaoImpl.findAllEmployees(-)")
    Criteria criteria = createEntityCriteria();
    LOGGER.info("OUT EmployeeDaoImpl.findAllEmployees(-)");
    return (List<Employee>criteria.list();
    
  }

  public Employee findEmployeeBySsn(String ssn) {
    LOGGER.info("IN EmployeeDaoImpl.findEmployeeBySsn(-)")
    Criteria criteria = createEntityCriteria();
    criteria.add(Restrictions.eq("ssn", ssn));
    LOGGER.info("OUT EmployeeDaoImpl.findEmployeeBySsn(-)")
    return (Employeecriteria.uniqueResult();
  }
}


This is Employee.java file having the source code to execute business logic.


 

    
package com.cv.spring.mvc.model;

import java.math.BigDecimal;

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.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
/**
 @author Chandra Vardhan
 */
@Entity
@Table(name="EMPLOYEE")
public class Employee {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;

  @Size(min=3, max=50)
  @Column(name = "NAME", nullable = false)
  private String name;

  @NotNull
  @DateTimeFormat(pattern="MM/dd/yyyy"
  @Column(name = "JOINING_DATE", nullable = false)
  @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
  private LocalDate joiningDate;

  @NotNull
  @Digits(integer=8, fraction=2)
  @Column(name = "SALARY", nullable = false)
  private BigDecimal salary;
  
  @NotEmpty
  @Column(name = "SSN", unique=true, nullable = false)
  private String ssn;

  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 LocalDate getJoiningDate() {
    return joiningDate;
  }

  public void setJoiningDate(LocalDate joiningDate) {
    this.joiningDate = joiningDate;
  }

  public BigDecimal getSalary() {
    return salary;
  }

  public void setSalary(BigDecimal salary) {
    this.salary = salary;
  }

  public String getSsn() {
    return ssn;
  }

  public void setSsn(String ssn) {
    this.ssn = ssn;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    result = prime * result + ((ssn == null: ssn.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (!(obj instanceof Employee))
      return false;
    Employee other = (Employeeobj;
    if (id != other.id)
      return false;
    if (ssn == null) {
      if (other.ssn != null)
        return false;
    else if (!ssn.equals(other.ssn))
      return false;
    return true;
  }

  @Override
  public String toString() {
    return "Employee [id=" + id + ", name=" + name + ", joiningDate="
        + joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";
  }  

}


This is EmployeeService.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.spring.mvc.service;

import java.util.List;

import com.cv.spring.mvc.model.Employee;
/**
 @author Chandra Vardhan
 */
public interface EmployeeService {

  Employee findById(int id);
  
  void saveEmployee(Employee employee);
  
  void updateEmployee(Employee employee);
  
  void deleteEmployeeBySsn(String ssn);

  List<Employee> findAllEmployees()
  
  Employee findEmployeeBySsn(String ssn);

  boolean isEmployeeSsnUnique(Integer id, String ssn);
  
}


This is EmployeeServiceImpl.java file having the service/business logic to call the DAO layer and get the information from database.


 

    
package com.cv.spring.mvc.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cv.spring.mvc.configuration.AppConfig;
import com.cv.spring.mvc.dao.EmployeeDao;
import com.cv.spring.mvc.model.Employee;
/**
 @author Chandra Vardhan
 */
@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
  
   private final static Logger LOGGER = Logger.getLogger(EmployeeServiceImpl.class);   

  @Autowired
  private EmployeeDao dao;
  
  public Employee findById(int id) {
    return dao.findById(id);
  }

  public void saveEmployee(Employee employee) {
    dao.saveEmployee(employee);
  }

  /*
   * Since the method is running with Transaction, No need to call hibernate update explicitly.
   * Just fetch the entity from db and update it with proper values within transaction.
   * It will be updated in db once transaction ends. 
   */
  public void updateEmployee(Employee employee) {
    LOGGER.info("IN EmployeeServiceImpl.updateEmployee(-)")
    Employee entity = dao.findById(employee.getId());
    if(entity!=null){
      entity.setName(employee.getName());
      entity.setJoiningDate(employee.getJoiningDate());
      entity.setSalary(employee.getSalary());
      entity.setSsn(employee.getSsn());
    }
    LOGGER.info("OUT EmployeeServiceImpl.updateEmployee(-)");
  }

  public void deleteEmployeeBySsn(String ssn) {
    dao.deleteEmployeeBySsn(ssn);
  }
  
  public List<Employee> findAllEmployees() {
    return dao.findAllEmployees();
  }

  public Employee findEmployeeBySsn(String ssn) {
    return dao.findEmployeeBySsn(ssn);
  }

  public boolean isEmployeeSsnUnique(Integer id, String ssn) {
    Employee employee = findEmployeeBySsn(ssn);
    return employee == null || ((id != null&& (employee.getId() == id)));
  }
  
}




This is pom.xml file having the entries of dependency jars and information to build the application .


	
<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"> xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.spring.mvc</groupId> <artifactId>SpringHibernateExample</artifactId> <packaging>war</packaging> <version>1.0</version> <name>SpringHibernateExample</name> <properties> <springframework.version>4.2.0.RELEASE</springframework.version> <hibernate.version>4.3.6.Final</hibernate.version> <mysql.version>5.1.31</mysql.version> <joda-time.version>2.3</joda-time.version> 6.9.4</testng.version> 1.10.19</mockito.version> 1.4.187</h2.version> 2.2</dbunit.version> <log4j-version>1.2.16</log4j-version> </properties> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.1-901.jdbc4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.3.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${joda-time.version}</version> </dependency> <dependency> <groupId>org.jadira.usertype</groupId> <artifactId>usertype.core</artifactId> <version>3.0.0.CR1</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> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springframework.version}</version> test </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>${testng.version}</version> test </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>${mockito.version}</version> test </dependency> <dependency> <groupId>dbunit</groupId> <artifactId>dbunit</artifactId> <version>${dbunit.version}</version> test </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <warSourceDirectory>src/main/webapp</warSourceDirectory> <warName>SpringHibernateExample</warName> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </pluginManagement> <finalName>SpringHibernateExample</finalName> </build> </project>


This is log4j.properties file having the entries for logging the information into the console/file.



#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


No comments:

Post a Comment