使用Spring MVC和JPA Eclipselinlk,没有可用于当前线程的实际事务的EntityManager

时间:2017-08-15 17:36:16

标签: java spring spring-mvc jpa eclipselink

我正在配置我的项目,我尝试了herethere中提到的解决方案,但我仍然遇到同样的错误。仅使用@PersistenceContext(type = PersistenceContextType.EXTENDED)我不会获得异常但不反映更新/保存/删除操作。

的applicationContext.xml

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
    <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
    <property name="showSql" value="true" />
</bean> 

<!--  This defines the entity manager factory with some custom properties -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="myPU"/>
    <property name="dataSource" ref="dataSourceTest" />
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
</bean>

<!-- This defines the hsqldb data source -->
<bean id="dataSourceTest" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="jdbc/myDS"/>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven/>

applicationDispatcher-servlet.xml中

<context:component-scan base-package="com.app.services,com.app.db,com.app.controller" />
<mvc:default-servlet-handler/>
<mvc:annotation-driven />

的web.xml

<display-name>MyApp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>


</welcome-file-list>
<servlet-name>applicationDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>

</servlet>


<servlet-mapping>
  <servlet-name>applicationDispatcher</servlet-name>
 <url-pattern>*.go</url-pattern>
    </servlet-mapping>
  <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

ApplicationController.java

    package com.app.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.app.model.Country;
import com.app.services.TestService;

@Controller
public class ApplicationController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private TestService serv;

    @RequestMapping(value="/hellotest.go", method = RequestMethod.POST, headers = "Accept=application/json")
    public @ResponseBody Country sayHelloTest2(@RequestBody Country country) {
        Country pais=new Country();
        pais.setCountryName("Yunaites");
        pais.setId(100);
        pais.setPopulation(1000);
        //model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
        //TestService serv=new TestService();
        serv.guardaTest();
        country.toString();
        return pais;
    }
}

TestService.java

    package com.app.services;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.PersistenceUnit;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.app.db.FirstRepository;
import com.app.entity.CatDivision;

@Service
public class TestService {
    @Autowired
    FirstRepository repo;

    public void guardaTest(){
        repo.register(null);
    }

    public FirstRepository getRepo() {
        return repo;
    }

    public void setRepo(FirstRepository repo) {
        this.repo = repo;
    }   

}

FirstRepository.java

    package com.app.db;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import com.app.entity.CatDivision;

@Transactional
//@Scope(proxyMode = ScopedProxyMode)
@Repository
public class FirstRepository {

    @PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }
    @Transactional
    public void register(CatDivision division) {
        // Save employee
        CatDivision div1=this.em.find(CatDivision.class, 1);
        System.out.println("Div:"+div1);
        CatDivision div=new CatDivision();
        div.setActivo(1);
        div.setNombre("Test");

        //div.setMbcareas(mbcareas);
        this.em.persist(div);
    }

}

CatDivision.java

    package com.app.entity;

import java.io.Serializable;
import javax.persistence.*;
import java.util.List;


/**
 * The persistent class for the mbcdivisio database table.
 * 
 */
@Entity
@Table(name="mbcdivisio")
@NamedQuery(name="CatDivision.findAll", query="SELECT c FROM CatDivision c")
public class CatDivision implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer iddivisio;

    private Integer activo;

    private String nombre;

    //bi-directional many-to-one association to CatArea
    @OneToMany(mappedBy="mbcdivisio")
    private List<CatArea> mbcareas;

    public CatDivision() {
    }

    public CatDivision(Integer iddivisio) {
        this.iddivisio=iddivisio;
    }

    public Integer getIddivisio() {
        return this.iddivisio;
    }

    public void setIddivisio(Integer iddivisio) {
        this.iddivisio = iddivisio;
    }

    public Integer getActivo() {
        return this.activo;
    }

    public void setActivo(Integer activo) {
        this.activo = activo;
    }

    public String getNombre() {
        return this.nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public List<CatArea> getMbcareas() {
        return this.mbcareas;
    }

    public void setMbcareas(List<CatArea> mbcareas) {
        this.mbcareas = mbcareas;
    }

    public CatArea addMbcarea(CatArea mbcarea) {
        getMbcareas().add(mbcarea);
        mbcarea.setMbcdivisio(this);

        return mbcarea;
    }

    public CatArea removeMbcarea(CatArea mbcarea) {
        getMbcareas().remove(mbcarea);
        mbcarea.setMbcdivisio(null);

        return mbcarea;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((iddivisio == null) ? 0 : iddivisio.hashCode());
        result = prime * result + ((nombre == null) ? 0 : nombre.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CatDivision other = (CatDivision) obj;
        if (iddivisio == null) {
            if (other.iddivisio != null)
                return false;
        } else if (!iddivisio.equals(other.iddivisio))
            return false;
        if (nombre == null) {
            if (other.nombre != null)
                return false;
        } else if (!nombre.equals(other.nombre))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "CatDivision [iddivisio=" + iddivisio + ", activo=" + activo + ", nombre=" + nombre + ", mbcareas="
                + mbcareas + "]";
    }

}

1 个答案:

答案 0 :(得分:0)

如果你想使用Transaction然后你需要启动Transaction并且在持久化之后你需要提交并关闭Transaction,你可以在下面的示例代码中使用Transaction:

  em.getTransaction( ).begin( );
  em.persist(div);
  em.getTransaction( ).commit( );
  em.close( );

也可以在您的配置中使用<tx:annotation-driven transaction-manager="transactionManager" />