我无法得到currentSession

时间:2015-03-16 00:07:30

标签: java spring hibernate

我是Java EE编程的初学者。当我尝试将员工保存在数据库中时收到此错误消息:

java.lang.NullPointerException
    at ma.lezar.ge.dao.EmployeesDAO.getCurrentSession(EmployeesDAO.java:48)
    at ma.lezar.ge.dao.EmployeesDAO.save(EmployeesDAO.java:59)
    at ma.lezar.ge.service.ServiceEmployees.save(ServiceEmployees.java:26)
    at ma.lezar.ge.bean.InscrirBean.valider(InscrirBean.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 28 more

这是 employeeDAO.java

package ma.lezar.ge.dao;

import java.util.List;
import java.util.Set;

import ma.lezar.ge.model.Employees;

import org.hibernate.Hibernate;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("EmployeesDAO")
@Transactional
public class EmployeesDAO implements IEmployeesDAO {
    private static final Logger log = LoggerFactory
            .getLogger(EmployeesDAO.class);
    // property constants
    public static final String NOM = "nom";
    public static final String NUM = "num";
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    protected void initDao() {
        // do nothing
    }

    public void save(Employees transientInstance) {
        //System.out.println(getCurrentSession().toString());
        //      log.debug("saving Employees instance");
        //      try {
            getCurrentSession().save(transientInstance);
            //          log.debug("save successful");
            //      } catch (RuntimeException re) {
            //          log.error("save failed", re);
            //          throw re;
            //      }
    }

    public void delete(Employees persistentInstance) {
        log.debug("deleting Employees instance");
        try {
            getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Employees findById(java.lang.Integer id) {
        log.debug("getting Employees instance with id: " + id);
        try {
            Employees instance = (Employees) getCurrentSession().get(
                    "ma.lezar.ge.model.Employees", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findAll() {
        log.debug("finding all Employees instances");
        try {
            String queryString = "from Employees";
            Query queryObject = getCurrentSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public static EmployeesDAO getFromApplicationContext(ApplicationContext ctx) {
        return (EmployeesDAO) ctx.getBean("EmployeesDAO");
    }
}

Employee.java

package ma.lezar.ge.model;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Employees entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "employees", catalog = "gest_emp")
public class Employees implements java.io.Serializable {

    // Fields

    private Integer id;
    private String nom;
    private Integer num;
    private Set<Compte> comptes = new HashSet<Compte>(0);

    // Constructors

    /** default constructor */
    public Employees() {
    }

    /** minimal constructor */
    public Employees(String nom, Integer num) {
        this.nom = nom;
        this.num = num;
    }

    /** full constructor */
    public Employees(String nom, Integer num, Set<Compte> comptes) {
        this.nom = nom;
        this.num = num;
        this.comptes = comptes;
    }

    // Property accessors
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name = "nom", nullable = false, length = 50)
    public String getNom() {
        return this.nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    @Column(name = "num", nullable = false)
    public Integer getNum() {
        return this.num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "employees")
    public Set<Compte> getComptes() {
        return this.comptes;
    }

    public void setComptes(Set<Compte> comptes) {
        this.comptes = comptes;
    }

}

InscrirBean.java

package ma.lezar.ge.bean;

import java.io.Serializable;

import javax.ejb.EJB;

import org.springframework.beans.factory.annotation.Autowired;

import ma.lezar.ge.dao.EmployeesDAO;
import ma.lezar.ge.model.Employees;
import ma.lezar.ge.service.IServiceEmployees;
import ma.lezar.ge.service.ServiceEmployees;

public class InscrirBean implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Autowired
    private ServiceEmployees serviceEmployees;

    private String nom;
    private Integer num;


    public String valider()
    {
        serviceEmployees = new ServiceEmployees();
        serviceEmployees.save(new Employees(nom, num));

        return "success";
    }


    public String getNom() {
        return nom;
    }


    public void setNom(String nom) {
        this.nom = nom;
    }


    public Integer getNum() {
        return num;
    }


    public void setNum(Integer num) {
        this.num = num;
    }


}

ServiceEmployee.java

package ma.lezar.ge.service;

import java.util.List;

import javax.annotation.Resource;





import ma.lezar.ge.dao.EmployeesDAO;
import ma.lezar.ge.dao.IEmployeesDAO;
import ma.lezar.ge.model.Employees;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

@Service("serviceEmployees")
public class ServiceEmployees implements IServiceEmployees {

@Resource
private EmployeesDAO employeesDao;

public void save(Employees transientInstance) {
    employeesDao = new EmployeesDAO();
    employeesDao.save(transientInstance);

}

public void delete(Employees persistentInstance) {

    employeesDao.delete(persistentInstance);

}

public Employees findById(java.lang.Integer id) {

        Employees instance = (Employees) employeesDao.findById(id);
        return instance;

}
public List findAll()
{
    return employeesDao.findAll();
    }

}

HibernateSessionFactory.java

package ma.lezar.ge.util;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * 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 HibernateSessionFactory {

    /** 
     * 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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;

    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

    static {
        try {
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }

    /**
     * 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.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.err.println("%%%% 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 org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

的applicationContext.xml

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


    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <property name="url"
            value="jdbc:mysql://localhost:3306/gest_emp">
        </property>
        <property name="username" value="root"></property>
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>ma.lezar.ge.model.Compte</value>
                <value>ma.lezar.ge.model.Employees</value></list>
        </property></bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <bean id="CompteDAO" class="ma.lezar.ge.dao.CompteDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="EmployeesDAO" class="ma.lezar.ge.dao.EmployeesDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
</beans>

1 个答案:

答案 0 :(得分:0)

您自己实例化employeesDao,而不是让Spring管理该类的DI。删除声明

employeesDao = new EmployeesDAO();
ServiceEmployees中的