使用 SpringFramework EntityManager 始终为 NULL

发布于 2025-01-05 18:54:20 字数 9305 浏览 0 评论 0原文

美好的一天,

我目前正在开发 Maven + Spring + Hibernate 项目。实际上,这只是一个测试项目,只是为了熟悉 Spring 如何与 Hibernate (+Maven) 配合使用。我已经设置并准备了必要的依赖项。即 Spring 的 appcontext.xml、Hibernate 的 persistence.xml、JPA/Persistence/Hibernate 的实体和 DAO 对象。

在调试过程中,我们发现 EntityManager 始终为 null。我不知道是什么原因造成的,因为我已经完成了 ff:

  1. 在我的控制器上自动装配
  2. 它在我的 applicationContext.xml 上将其声明为 bean
  3. 将我的 DAO 对象注释为 @Repository
  4. entityManagerFactorytransactionManagervendorAdapter 定义为我的 applicationContext.xml 上的 bean,

我一直在调试并整天尝试解决方法。不幸的是,我还没有解决这个问题。希望有人能够对这个问题有所启发。

以下是我的项目的代码和配置:

<--- 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_1_0.xsd"
version="1.0">
    <persistence-unit name="msh" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.msh.TblFileinfo</class>
    </persistence-unit>
</persistence>

<--- applicationContext.xml --->

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

    <!-- need to create database.properties file -->
    <context:property-placeholder location="classpath:database.properties"/>

    <context:component-scan base-package="com.msh"/>

    <!-- tell Spring that it should act on any @PersistenceContext and @Transactional annotations found in bean classes -->
    <!-- <tx:annotation-driven/> -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean class="com.msh.TblFileinfoHome" />
    <bean class="com.msh.TblFileinfo" />

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <!-- <property name="databasePlatform" value="${platform}" /> -->
        <property name="showSql" value="${database.showSql}" />
        <property name="generateDdl" value="${database.generateDdl}" />
    </bean>

    <bean id="entityManagerFactory" class="org.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="msh" />
        <property name="dataSource" ref="dataSource" />
        <!-- <property name="loadTimeWeaver" class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /> -->
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean  id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driverClassName}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
    </bean>
</beans>

<--- 主要java代码--->

package com.msh;

public class MavenSpringHibernate {

    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Sample s = new Sample();
        s.persist();
    }
}

<--- DAO --->

package com.msh;

import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Home object for domain model class TblFileinfo.
 * @see com.trendmicro.grid.mshPackage.TblFileinfo
 * @author Hibernate Tools
 */

/**
@Stateless
@Repository
@Transactional
*/

@Repository
public class TblFileinfoHome {

    private static final Log log = LogFactory.getLog(TblFileinfoHome.class);

    @PersistenceContext(unitName="msh")
    private EntityManager entityManager;

    @Transactional
    public void persist(TblFileinfo transientInstance) {
        log.debug("persisting TblFileinfo instance");
        try {
            entityManager.persist(transientInstance);
            log.debug("persist successful");
        }
        catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    @Transactional
    public void remove(TblFileinfo persistentInstance) {
        log.debug("removing TblFileinfo instance");
        try {
            entityManager.remove(persistentInstance);
            log.debug("remove successful");
        }
        catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    @Transactional
    public TblFileinfo merge(TblFileinfo detachedInstance) {
        log.debug("merging TblFileinfo instance");
        try {
            TblFileinfo result = entityManager.merge(detachedInstance);
            log.debug("merge successful");
            return result;
        }
        catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    @Transactional
    public TblFileinfo findById( Long id) {
        log.debug("getting TblFileinfo instance with id: " + id);
        try {
            TblFileinfo instance = entityManager.find(TblFileinfo.class, id);
            log.debug("get successful");
            return instance;
        }
        catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
}

--- 实体 ---

package com.msh;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * TblFileinfo generated by hbm2java
 */
@Entity
@Table(name="tbl_fileinfo"
    ,catalog="behavior"
)
public class TblFileinfo  implements java.io.Serializable {


     private Long fileId;
     private String filename;
     private String filetype;

    public TblFileinfo() {
    }

    public TblFileinfo(String filename, String filetype) {
       this.filename = filename;
       this.filetype = filetype;
    }

     @Id @GeneratedValue(strategy=GenerationType.AUTO)


    @Column(name="file_id", unique=true, nullable=false)
    public Long getFileId() {
        return this.fileId;
    }

    public void setFileId(Long fileId) {
        this.fileId = fileId;
    }


    @Column(name="filename", length=200)
    public String getFilename() {
        return this.filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }


    @Column(name="filetype", length=50)
    public String getFiletype() {
        return this.filetype;
    }

    public void setFiletype(String filetype) {
        this.filetype = filetype;
    }
}

<--- 示例类控制器 --->

package com.msh;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.trendmicro.grid.msh.TblFileinfo;
import com.trendmicro.grid.msh.TblFileinfoHome;


@Transactional
public class Sample {
    @Autowired
    private TblFileinfo tinfo;
    private TblFileinfoHome tinfoh;

    public Sample()
    {
        tinfo = new TblFileinfo("c:/jayson/murillo/pryde.exe", "uv_win32");
        tinfoh = new TblFileinfoHome();
    }

    public void persist()
    {
        tinfoh.persist(tinfo);
    }
}

再次希望有人能对此提供反馈。提前致谢!

Good day,

I've been currently working on a Maven + Spring + Hibernate project. Actually, this is just a test project just to get familiar on how Spring works with Hibernate (+Maven). I've already setup and prepare the necessary dependencies. i.e. the appcontext.xml for Spring, the persistence.xml for Hibernate, the entity and DAO objects for JPA/Persistence/Hibernate.

During debug, it's observed that the EntityManager is always null. I don't know what's causing this because I've done the ff:

  1. Autowire it on my controller
  2. Declared it as a bean on my applicationContext.xml
  3. Annotate my DAO object as @Repository
  4. Defined entityManagerFactory, transactionManager and vendorAdapter as beans on my applicationContext.xml

I've been debugging and trying workarounds all day. Unfortunately, I haven't resolve this yet. Hope someone can shed some light on this issue.

Below are the codes and configurations of my project:

<--- 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_1_0.xsd"
version="1.0">
    <persistence-unit name="msh" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.msh.TblFileinfo</class>
    </persistence-unit>
</persistence>

<--- applicationContext.xml --->

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

    <!-- need to create database.properties file -->
    <context:property-placeholder location="classpath:database.properties"/>

    <context:component-scan base-package="com.msh"/>

    <!-- tell Spring that it should act on any @PersistenceContext and @Transactional annotations found in bean classes -->
    <!-- <tx:annotation-driven/> -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean class="com.msh.TblFileinfoHome" />
    <bean class="com.msh.TblFileinfo" />

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <!-- <property name="databasePlatform" value="${platform}" /> -->
        <property name="showSql" value="${database.showSql}" />
        <property name="generateDdl" value="${database.generateDdl}" />
    </bean>

    <bean id="entityManagerFactory" class="org.org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="msh" />
        <property name="dataSource" ref="dataSource" />
        <!-- <property name="loadTimeWeaver" class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" /> -->
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean  id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driverClassName}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.username}" />
        <property name="password" value="${database.password}" />
    </bean>
</beans>

<--- Main java code --->

package com.msh;

public class MavenSpringHibernate {

    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Sample s = new Sample();
        s.persist();
    }
}

<--- DAO --->

package com.msh;

import javax.ejb.Stateless;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Home object for domain model class TblFileinfo.
 * @see com.trendmicro.grid.mshPackage.TblFileinfo
 * @author Hibernate Tools
 */

/**
@Stateless
@Repository
@Transactional
*/

@Repository
public class TblFileinfoHome {

    private static final Log log = LogFactory.getLog(TblFileinfoHome.class);

    @PersistenceContext(unitName="msh")
    private EntityManager entityManager;

    @Transactional
    public void persist(TblFileinfo transientInstance) {
        log.debug("persisting TblFileinfo instance");
        try {
            entityManager.persist(transientInstance);
            log.debug("persist successful");
        }
        catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    @Transactional
    public void remove(TblFileinfo persistentInstance) {
        log.debug("removing TblFileinfo instance");
        try {
            entityManager.remove(persistentInstance);
            log.debug("remove successful");
        }
        catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    @Transactional
    public TblFileinfo merge(TblFileinfo detachedInstance) {
        log.debug("merging TblFileinfo instance");
        try {
            TblFileinfo result = entityManager.merge(detachedInstance);
            log.debug("merge successful");
            return result;
        }
        catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    @Transactional
    public TblFileinfo findById( Long id) {
        log.debug("getting TblFileinfo instance with id: " + id);
        try {
            TblFileinfo instance = entityManager.find(TblFileinfo.class, id);
            log.debug("get successful");
            return instance;
        }
        catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
}

--- Entity ---

package com.msh;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * TblFileinfo generated by hbm2java
 */
@Entity
@Table(name="tbl_fileinfo"
    ,catalog="behavior"
)
public class TblFileinfo  implements java.io.Serializable {


     private Long fileId;
     private String filename;
     private String filetype;

    public TblFileinfo() {
    }

    public TblFileinfo(String filename, String filetype) {
       this.filename = filename;
       this.filetype = filetype;
    }

     @Id @GeneratedValue(strategy=GenerationType.AUTO)


    @Column(name="file_id", unique=true, nullable=false)
    public Long getFileId() {
        return this.fileId;
    }

    public void setFileId(Long fileId) {
        this.fileId = fileId;
    }


    @Column(name="filename", length=200)
    public String getFilename() {
        return this.filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }


    @Column(name="filetype", length=50)
    public String getFiletype() {
        return this.filetype;
    }

    public void setFiletype(String filetype) {
        this.filetype = filetype;
    }
}

<--- Sample class controller --->

package com.msh;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.trendmicro.grid.msh.TblFileinfo;
import com.trendmicro.grid.msh.TblFileinfoHome;


@Transactional
public class Sample {
    @Autowired
    private TblFileinfo tinfo;
    private TblFileinfoHome tinfoh;

    public Sample()
    {
        tinfo = new TblFileinfo("c:/jayson/murillo/pryde.exe", "uv_win32");
        tinfoh = new TblFileinfoHome();
    }

    public void persist()
    {
        tinfoh.persist(tinfo);
    }
}

Again, hope someone can provide feedback on this. Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

っ〆星空下的拥抱 2025-01-12 18:54:20

您不会在主类中加载 Spring 上下文:

public class MavenSpringHibernate {

    /**
     * @param args
     */

    public static void main(String[] args) {

        ApplicationContext context =
                new ClassPathXmlApplicationContext(new String[] {"classpath:/PATH/TO/applicationContext.xml"});

        Sample s = context.getBean(Sample.class);
        s.persist();
    }
}

You do not load your Spring context in your main class :

public class MavenSpringHibernate {

    /**
     * @param args
     */

    public static void main(String[] args) {

        ApplicationContext context =
                new ClassPathXmlApplicationContext(new String[] {"classpath:/PATH/TO/applicationContext.xml"});

        Sample s = context.getBean(Sample.class);
        s.persist();
    }
}
好多鱼好多余 2025-01-12 18:54:20

你甚至还没有开始春天!

Sample s = new Sample();

Sample 是一个 Spring bean。您必须首先启动应用程序上下文并从那里获取 bean。请参阅 @nico_ekito 的回答:

public static void main(String[] args) {
    ApplicationContext context =
         new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
    Sample s = context.getBean(Sample.class);
    s.persist();
}

启动上下文后(这可能会导致一些错误),请更正以下内容:

  • 删除此内容:

    tinfoh = new TblFileinfoHome();
    

    注释字段:

    <前><代码>@Autowired
    私人 TblFileinfoHome tiinfoh;

  • 您不应该自动装配实体类:

    @Autowired //去掉这个注解
    私有 TblFileinfo tinfo;
    

You aren't even starting Spring!

Sample s = new Sample();

Sample is a Spring bean. You must first start the application context and fetch the bean from there. See @nico_ekito's answer:

public static void main(String[] args) {
    ApplicationContext context =
         new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
    Sample s = context.getBean(Sample.class);
    s.persist();
}

Once you start the context (which will probably result with some errors), correct the following:

  • Remove this:

    tinfoh = new TblFileinfoHome();
    

    annotate field with:

    @Autowired
    private TblFileinfoHome tinfoh;
    
  • you should not be autowiring entity class:

    @Autowired                //remove this annotation
    private TblFileinfo tinfo;
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文