【问题标题】:entity manager not correctly injected by spring and gives java.lang.NullPointerException [duplicate]spring 没有正确注入实体管理器并给出 java.lang.NullPointerException [重复]
【发布时间】:2016-04-08 11:03:50
【问题描述】:

我是在 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(虽然它真的很乱,所以如果你发现一些错误请告诉)

<?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>

提前非常感谢你

【问题讨论】:

  • 为什么 classpath*:META-INF/persistence.xml 中的 * ... 不应该是简单的 ?
  • @Mohamed ElȜalamy 你能添加 Stacktrace 的异常吗?
  • @MohamedElȜalamy 将 &lt;context:component-scan base-package="com.iticsys.GBO.dao" /&gt; 替换为 &lt;context:component-scan base-package="com.iticsys.GBO" /&gt; 并从您的 applicationContext.xml 文件中删除 bean 声明 daoservice,因为它们已经在使用 spring 注释并且带有上述标签被自动检测到。

标签: spring hibernate jpa entitymanager


【解决方案1】:

在类 IUserDAOImpl 的实现中,你应该实例化 EntityManager 的 Object 像

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

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

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

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

【讨论】:

  • 这可能有效,但我希望它在 spring 自动注入。
  • 看看这个: [docs.spring.io/spring/docs/2.5.x/reference/…他们正在通过set...()方法设置private reference。这意味着您必须传递 EntityManager 的引用才能使该类正常工作。如果你不这样做,它会抛出NullPointerException
【解决方案2】:
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;
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2014-07-26
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多