while using hibernate 5 with spring mvc 4, every dao is getting session factory or session is null

454 views Asked by At

EmployeeDAOImpl.java(My dao implementation)

    package com.crud.dao.implementations;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.springframework.stereotype.Repository;

import com.crud.dao.interfaces.EmployeeDAO;
import com.crud.model.Employee;
@Repository
public class EmployeeDAOImpl implements EmployeeDAO{

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    @Transactional
    public void insertSingleEmployee(Employee e) {
        Session session = sessionFactory.getCurrentSession();
        if(session!=null) {
            try {
                session.beginTransaction();
                session.persist(e);
                session.getTransaction().commit();
            } catch (Exception e2) {
                if(session.getTransaction().getStatus()== TransactionStatus.ACTIVE || session.getTransaction().getStatus()== TransactionStatus.MARKED_ROLLBACK) {
                    session.getTransaction().rollback();
                }
            }
            finally {
                session.close();
            }
        }
        else {
            System.out.println("session is null "); 
        }
    }

    @Transactional
    public void updateSingleEmpployee(Employee e) {
        Session session = this.sessionFactory.getCurrentSession();
        try {
            session.beginTransaction();
            session.update(e);
            session.getTransaction().commit();
        } catch (Exception e2) {
            if(session.getTransaction().getStatus()==TransactionStatus.ACTIVE || session.getTransaction().getStatus()== TransactionStatus.MARKED_ROLLBACK) {
                session.getTransaction().rollback();
            }
        }
        finally {
            session.close();
        }
    }

    @Transactional
    public void deleteSingleEmployee(long employeeID) {
        Session session = this.sessionFactory.getCurrentSession();
        try {
            session.beginTransaction();
            Employee e = (Employee) session.load(Employee.class, new Long(employeeID));
            if(e!=null)
                session.delete(e);
            session.getTransaction().commit();
        } catch (Exception e) {
            if(session.getTransaction().getStatus()== TransactionStatus.ACTIVE || session.getTransaction().getStatus()==TransactionStatus.MARKED_ROLLBACK) {
                session.getTransaction().rollback();
            }
        }
        finally {
            session.close();
        }
    }

    @SuppressWarnings("unchecked")
    @Transactional
    public List<Employee> listOfEmployees(){
        Session session = this.sessionFactory.getCurrentSession();
        List<Employee> listOfEmployees = null;
        try {
            session.beginTransaction();
            listOfEmployees = session.createQuery("from Employee").list();
            session.getTransaction().commit();
            session.close();
        } catch (Exception e) {
            if(session.getTransaction().getStatus()== TransactionStatus.ACTIVE || session.getTransaction().getStatus()==TransactionStatus.MARKED_ROLLBACK) {
                session.getTransaction().rollback();
            }
        }
        finally {
            session.close();
        }
        return listOfEmployees;
    }
}

then my spring dispatcher xml file spring_dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

        <context:component-scan base-package="com.crud.controllers" />
        <context:annotation-config />
        <mvc:annotation-driven />
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix">
                <value>/WEB-INF/pages/</value>
            </property>
            <property name="suffix">
                <value>.jsp</value>
            </property>
        </bean>
        <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://127.0.0.1:3306/university" />
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        <bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
            <property name="dataSource" ref="myDataSource" />
            <property name="annotatedClasses">
                <list>
                    <value>com.crud.model.Employee</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                    <prop key="hibernate.c3p0.min_size">5</prop>
                    <prop key="hibernate.c3p0.max_size">30</prop>
                    <prop key="hibernate.c3p0.timeout">60</prop>
                    <prop key="hibernate.hbm2ddl.auto">create</prop>
                    <prop key="hibernate.show_sql">true</prop>
                </props>
            </property>
        </bean>

        <bean id="employeeDao" class="com.crud.dao.implementations.EmployeeDAOImpl">
            <property name="sessionFactory" ref="mySessionFactory" />
        </bean>
        <tx:annotation-driven transaction-manager="transactionManager"/>
        <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
            <property name="sessionFactory" ref="mySessionFactory" />
        </bean>
 </beans>

and this is my controller class EmployeeController.java

package com.crud.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.crud.dao.DAOFactory;
import com.crud.model.Employee;

@Controller
@ControllerAdvice
@RequestMapping(value="/employee")
public class EmployeeController {

    @RequestMapping(value="/addPerson", method=RequestMethod.GET)
    public String addForm() {
        return "addPerson";
    }

    @RequestMapping(value="/save", method=RequestMethod.POST)
    public String addEmployee(@ModelAttribute("employee") Employee e, BindingResult result) {
        if(result.hasErrors())
            return "addPerson";
        else {
            DAOFactory mysqlFactory = DAOFactory.getDAOFactory(1);
            if(e!=null)
                mysqlFactory.getEmployeeDAO().insertSingleEmployee(e);
        }

        return "hello"; 
    }
}

and this my entity class employee

package com.crud.model;

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.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
@Table(name="employee")
public class Employee {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;
    private String firstName;
    private String lastName;
    private String mobile;
    private String address;
    private String gender;
    private String email;

    public Employee() {

    }

    public Employee(long id, String firstName, String lastName, String mobile, String address, String gender,
            String email) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.mobile = mobile;
        this.address = address;
        this.gender = gender;
        this.email = 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 getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

[this is the error i am getting while trying to save in the database the form's detail filled by the user in a browser against the employee entity class. but it is getting null pointer exception.][1]

hibernate cfg file settings is here

<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/school_driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.connection.autocommit">false</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.hbm2ddl.auto">validate</property>

and my configuration for session factory creation

StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder().build();
        hibernateSessionFactory = metadata.getSessionFactoryBuilder().build();
        return hibernateSessionFactory;
1

There are 1 answers

3
Kshitij Mandloi On

Try using @Qualifier("mySessionFactory") where you have autowired the SessionFactory instance in DAO class.