实体管理器没有被spring正确注入并给出了java.lang.NullPointerException

时间:2016-04-08 11:03:51

标签: spring hibernate jpa entitymanager

我是JAVA EE中使用框架的新手 所以当我试图调用实体管理器的方法时 它抛出一个java.lang.NullPointerException 所以我想写我写的东西 这是我的dao实现的一个例子

@Repository
@Transactional
public class IUserDAOImpl implements IUserDAO{

    @PersistenceContext
    private EntityManager em;

    public void addUser(User u) {
        em.persist(u);
    }   
}

这是我的服务

@Service
public class IUserServiceImpl implements IUserService {

@Autowired
private IUserDAO dao = new IUserDAOImpl();

public void setDao(IUserDAO dao) {
    this.dao = dao;
}

public void addUser(User u) {
    dao.addUser(u);     
}

这是我的动作类

public class ConnectionAction extends ActionSupport {

User c = new User("a","b","c",11,"d",true);

@Autowired
public IUserService service;


public String execute() throws Exception {
    service.addUser(c);
        return SUCCESS;
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Struts Blank</display-name>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<context-param>
<param-name>contextConfiguration</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>

applicationContext.xml(虽然它真的搞砸了所以如果你注意到某些错误的plz告诉)

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:tx="http://www.springframework.org/schema/tx"     xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"     xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/util     http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="dao"
class="com.iticsys.GBO.dao.IUserDAOImpl">
</bean>

<bean id="service"
class="com.iticsys.GBO.services.IUserServiceImpl">
<property name="dao" ref="dao"></property>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/GBO1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>

<bean id="persistenceUnitManager"
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<value>classpath*:META-INF/persistence.xml</value>
</property>
<property name="defaultDataSource" ref="dataSource"> </property>
</bean>

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="persistenceUnit" /> 
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean> 
<tx:annotation-driven transaction-manager="transactionManager" /> 
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.iticsys.GBO.dao" />
</beans>

的persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="persistenceUnit"
    transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>


    <properties>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/GBO1" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="" />

        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.hbm2ddl.auto" value="update" />
    </properties>
</persistence-unit>

非常感谢你提前

2 个答案:

答案 0 :(得分:0)

IUserDAOImpl 类的实现中,您应该实例化EntityManager的对象

private EntityManager em = new EntityManager(/*constructor parameter if any*/);

或者您可以指定您可以在其他子类中创建的EntityManager对象的引用,例如IUserServiceImplConnectionAction

为此,您可以在课程 IUserDAOImpl 中添加一个接收该引用的方法。

public void setEntityManager(EntityManager em_ref ){ em = em_ref;}

答案 1 :(得分:0)

public class HibernateUtil {

static Logger logger = Logger.getLogger(HibernateUtil.class);

private static final String FAILED_TO_CREATE_SESSION_FACTORY_OBJECT = "Failed to create sessionFactory object.";
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;

private static SessionFactory buildSessionFactory() {

try {
    Configuration configuration = new Configuration();
    configuration.configure("./hibernate.cfg.xml");

    configuration.addAnnotatedClass(Calzz.class);

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

    return configuration.buildSessionFactory(serviceRegistry);

} catch (Throwable ex) {

    logger.debug(FAILED_TO_CREATE_SESSION_FACTORY_OBJECT + ex);
    throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}