【问题标题】:Entity Manager NULL - Spring MVC JPA实体管理器 NULL - Spring MVC JPA
【发布时间】:2015-06-22 15:37:01
【问题描述】:

在以下代码中,entityManager 为空。我究竟做错了什么?我需要自动注入entityManager

我的对象模型:

@Entity
@Table(name = "jlocalidades", catalog = "7jogos")
public class Jlocalidades implements java.io.Serializable {

    private Integer id;
    private String nome;
    private String descricao;

    public Jlocalidades() {
    }

    public Jlocalidades(String nome, String descricao) {
        this.nome = nome;
        this.descricao = descricao;
    }

    @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 = "Nome", nullable = false, length = 200)
    public String getNome() {
        return this.nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    @Column(name = "Descricao", nullable = false, length = 200)
    public String getDescricao() {
        return this.descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    }

我的小服务程序

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


    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->

<context:component-scan base-package="com.dtr.oas" />
 <context:annotation-config/>



        <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
   <!--     <resources mapping="/resources/**" location="/resources/" /> -->

      <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>



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

    <bean id="mysqlDS"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://192.168.254.38:3306/7jogos" />
        <property name="username" value="root" />
        <property name="password" value="6+1Log.pt" />
    </bean>

     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="mysqlDS"/>
      <property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" />
    </bean>

        <tx:annotation-driven/>

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

</beans>    

我的坚持

<?xml version="1.0" encoding="UTF-8" ?>
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
    <!-- shouldn't be valid for java SE per specification, but it works for EclipseLink ... -->
    <class>com.dtr.oas.model.Jlocalidades</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>

        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.254.38:3306/7jogos" />
        <property name="javax.persistence.jdbc.user" value="root" />
        <property name="javax.persistence.jdbc.password" value="6+1Log.pt" />

        <!-- EclipseLink should create the database schema automatically -->
        <property name="eclipselink.ddl-generation" value="create-tables" />
        <property name="eclipselink.ddl-generation.output-mode" value="database" />
        <property name="eclipselink.logging.level" value="SEVERE"/>                
    </properties>

</persistence-unit>

给出错误的控制器

     package com.dtr.oas.model;



import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.setelog.model.Jcelulas;



public class JlocalidadesHome implements IJlocalidadesHome {

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


@Autowired
 private SessionFactory sessionFactory;

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


@PersistenceContext
private EntityManager entityManager;

public void persist(Jlocalidades transientInstance) {
    log.debug("persisting Jlocalidades instance");
    try {

        EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();
        entityManager.persist(transientInstance);
        log.debug("persist successful");
    } catch (RuntimeException re) {
        log.error("persist failed", re);
        throw re;
    }
}

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

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

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

@Transactional
public List<Jlocalidades> All (){
    log.debug("getting all Jlocalidades");
    try {

        List<Jlocalidades> instance = entityManager.createQuery("SELECT * FROM jlocalidades").getResultList(); 
        log.debug("get successful");
        return instance;
    } catch (RuntimeException re) {
        log.error("get failed", re);
        throw re;
    }
   }
}

【问题讨论】:

  • 您应该向我们展示控制器的完整代码(包名、类上的注释)以及向我们展示如何使用它的代码。
  • 谢谢您的回复。我发布了我的控制器的完整代码。
  • 使用 spring 示例锻炼 jpa 并在此处发布..
  • 如果你需要最好的帮助,你真的应该创建一个更小的、包含的示例:sscce.org

标签: java spring hibernate spring-mvc jpa


【解决方案1】:

您需要在控制器类上使用@Controller,以便 spring 将 entityManager 注入其中。既然您希望 Spring 注入 EntityManager,请不要这样做:

EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();

一般情况下,只有在没有容器的情况下运行时才会调用Persistence.createEntityManagerFactory()

用于在 Java 中获取 EntityManagerFactory 的引导类 SE 环境。

您可以通过更改 EntityManager 配置而不使用 persistence.xml:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="mysqlDS"/>
    <property name="packagesToScan" value="YOUR.ENTITY.PKG" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generatedDdl" value="true" />
            <property name="databasePlatform" value="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </bean>
    </property>
</bean>

【讨论】:

    【解决方案2】:

    控制器是如何实例化的?它需要是一个 spring 管理的 bean。

    您在 conf 文件中定义了类路径扫描 xml。但是JlocalidadesHome 没有标注控制器/组件。

    顺便说一句,使用控制器从请求中获取输入,然后它应该调用服务类......并且服务类与数据层类交互

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2014-09-06
      • 2019-05-25
      相关资源
      最近更新 更多