Spring + hibernate泛型dao getsession()java.lang.NullPointerException

时间:2014-02-28 06:24:58

标签: java spring hibernate

genericDOa接口

package com.iverve.telecom.Dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;

public interface GenericDAO extends Serializable {
    Object findById(Class<?> persistentClass, Long id, boolean lock);
    List<?> findByCriteria(Class<?> persistentClass, Criterion... criterion);
    Object saveOrUpdate(Class<?> clazz,Object object);
    boolean saveOrUpdate(Collection<?> peristableCollection);
    void delete(Class<?> clazz, Long id);
    void delete(List<?> list);
}

扩展GenericDAO的GenericDAOImpl类

package com.iverve.telecom.DAOImpl;

import java.util.Collection;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.iverve.telecom.Dao.GenericDAO;


@Transactional

public class GenericDAOImpl implements GenericDAO {

    private SessionFactory sessionFactory;

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

    private Session session;
    public final Session getSession() {
        session = sessionFactory.getCurrentSession();
        if (session == null) {
            session = sessionFactory.openSession();
        }
        return session;
    }

    public final Object findById(final Class<?> clazz, final Long id, final boolean lock) {
        Object entity = null;
        session = getSession();
        if (lock) {
            entity = session.load(clazz, id, LockMode.UPGRADE);
        } else {
            entity = session.load(clazz, id);
        }
        return entity;
    }

    public final Object saveOrUpdate(final Class<?> clazz, final Object object) {

        try {
            session = getSession();
            session.saveOrUpdate(object);
        } catch (Exception ex) {
        }
        return object;
    }

    public final boolean saveOrUpdate(final Collection<?> persistableCollection) {
        boolean flag = false;
        try {
            for (Object persistableObj : persistableCollection) {
                session.saveOrUpdate(persistableObj);
            }
            flag = true;
        } catch (Exception ex) {
            ex.printStackTrace();
            flag = false;
        }
        return flag;
    }

    public final List<?> findByCriteria(final Class<?> currentPersistantClass, final Criterion... criterion) {
        final Criteria crit = getSession().createCriteria(currentPersistantClass);
        for (final Criterion c : criterion) {
            crit.add(c);
        }
        return crit.list();
    }

    public final void delete(final Class clazz, final List<Long> ids) {
        try {
            for (Long surrogateKey : ids) {
                final Object obj = getSession().load(clazz, surrogateKey);
                session.delete(obj);
            }
            getSession().flush();
        } catch (Exception ex) {
         }
    }

    public final void delete(final Class<?> clazz, final Long persistentId) {
        try {
            session.delete(findById(clazz, persistentId, false));
        } catch (Exception ex) {
        }
    }

    public void delete(List<?> ids) {
        // TODO Auto-generated method stub

    }    
}

状态Pojo是主表pojo

package com.iverve.telecom.pojo;

// Generated 27 Feb, 2014 4:02:03 PM by Hibernate Tools 3.4.0.CR1

import java.util.HashSet;
import java.util.Set;
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;

/**
 * State generated by hbm2java
 */
@Entity
@Table(name = "state", catalog = "telecom_mgmt")
public class State implements java.io.Serializable {

    private Long stateId;
    private String state;
    private Set<Admin> admins = new HashSet<Admin>(0);
    private Set<CompanyAdmin> companyAdmins = new HashSet<CompanyAdmin>(0);
    private Set<User> users = new HashSet<User>(0);
    private Set<CompanyDetail> companyDetails = new HashSet<CompanyDetail>(0);
    private Set<City> cities = new HashSet<City>(0);

    public State() {
    }

    public State(String state) {
        this.state = state;
    }

    public State(String state, Set<Admin> admins,
            Set<CompanyAdmin> companyAdmins, Set<User> users,
            Set<CompanyDetail> companyDetails, Set<City> cities) {
        this.state = state;
        this.admins = admins;
        this.companyAdmins = companyAdmins;
        this.users = users;
        this.companyDetails = companyDetails;
        this.cities = cities;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "state_id", unique = true, nullable = false)
    public Long getStateId() {
        return this.stateId;
    }

    public void setStateId(Long stateId) {
        this.stateId = stateId;
    }

    @Column(name = "state", nullable = false, length = 45)
    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "state")
    public Set<Admin> getAdmins() {
        return this.admins;
    }

    public void setAdmins(Set<Admin> admins) {
        this.admins = admins;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "state")
    public Set<CompanyAdmin> getCompanyAdmins() {
        return this.companyAdmins;
    }

    public void setCompanyAdmins(Set<CompanyAdmin> companyAdmins) {
        this.companyAdmins = companyAdmins;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "state")
    public Set<User> getUsers() {
        return this.users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "state")
    public Set<CompanyDetail> getCompanyDetails() {
        return this.companyDetails;
    }

    public void setCompanyDetails(Set<CompanyDetail> companyDetails) {
        this.companyDetails = companyDetails;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "state")
    public Set<City> getCities() {
        return this.cities;
    }

    public void setCities(Set<City> cities) {
        this.cities = cities;
    }

}

扩展GenericDAO的stateDAO

package com.iverve.telecom.Dao;

import java.io.Serializable;
import java.util.List;
import com.iverve.telecom.pojo.State;

public interface StateDAO extends GenericDAO, Serializable {

    List<State> displayState(); 
}

扩展GenericDAOImpl的stateDAOImpl

package com.iverve.telecom.DAOImpl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;

import com.iverve.telecom.Dao.StateDAO;
import com.iverve.telecom.pojo.State;

public class StateDAOImpl extends GenericDAOImpl implements StateDAO {


    @Override
    public List<State> displayState() {
        // TODO Auto-generated method stub
        Criteria criteria = getSession().createCriteria(State.class);
        List<State> state = criteria.list();
        Iterator it = state.iterator();
        List<State> stateList = new ArrayList<State>();
        while (it.hasNext()) {
            State getState = (State) it.next();
            State setState = new State();
            setState.setStateId(getState.getStateId());
            setState.setState(getState.getState());
            stateList.add(setState);
        }
        return stateList;
    }
}

application-context.xml这个文件位于scr

<?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:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config/> 
    <context:component-scan base-package="com.iverve.telecom.DAOImpl"/> 
    <bean id="exampleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/telecom_mgmt"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="exampleSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource"><ref local="exampleDataSource"/></property>
         <property name="hibernateProperties">
           <props>
             <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
             <prop key="hibernate.show_sql">true</prop>
             <prop key="hibernate.hbm2ddl.auto">update</prop>
           </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>com.iverve.telecom.pojo.Admin</value>
                <value>com.iverve.telecom.pojo.City</value>
                <value>com.iverve.telecom.pojo.CompanyAdmin</value>
                <value>com.iverve.telecom.pojo.CompanyBranch</value>
                <value>com.iverve.telecom.pojo.CompanyDetail</value>
                <value>com.iverve.telecom.pojo.CompanyState</value>
                <value>com.iverve.telecom.pojo.CompanyZonel</value>
                <value>com.iverve.telecom.pojo.Complain</value>
                <value>com.iverve.telecom.pojo.Faqs</value>
                <value>com.iverve.telecom.pojo.Feedback</value>
                <value>com.iverve.telecom.pojo.Inquiry</value>
                <value>com.iverve.telecom.pojo.State</value>
                <value>com.iverve.telecom.pojo.SupportEngCompany</value>
                <value>com.iverve.telecom.pojo.SupportEngComplain</value>
                <value>com.iverve.telecom.pojo.User</value>
            </list>
        </property>     
    </bean>

    <bean id="productRepository" class="com.iverve.telecom.DAOImpl.GenericDAOImpl">
        <property name="sessionFactory" ref="exampleSessionFactory" />
    </bean>


<!--  Transactional settings required for the Hibernate example to work. -->
    <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="exampleSessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />

</beans>

仅调用

的UserController
package com.iverve.telecom.controller;

import java.io.IOException;
import java.util.List;

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.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.iverve.telecom.DAOImpl.StateDAOImpl;
import com.iverve.telecom.DAOImpl.UserDaoImpl;
import com.iverve.telecom.Dao.StateDAO;
import com.iverve.telecom.Dao.UserDAO;
import com.iverve.telecom.pojo.State;

/**
 * Servlet implementation class UserController
 */
@WebServlet("/UserController")
public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        StateDAO state = new StateDAOImpl();
        List<State> listState = state.displayState();
        request.setAttribute("StateList", listState);
        request.getRequestDispatcher("/Telecom_Mgmt/User/jsp/registration.jsp")
                .forward(request, response);

    }
}

1 个答案:

答案 0 :(得分:5)

您自己实例化该课程

StateDAO state = new StateDAOImpl();

你没有从Spring获得一个bean。它显然不是Spring托管bean,因此没有任何注入发生。

更重要的是,你在Servlet中使用它,它也不是Spring托管bean。它由Servlet容器管理。您必须使用herehere所述的技术之一来实现这一目标。