spring-mvc 3.0.5:实例化JPA实体管理器的首选方法是什么

时间:2010-11-15 01:09:31

标签: java spring jpa dependency-injection persistence

我目前的工作代码:

EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("TT-SpringMVCPU");
EntityManager em = emf.createEntityManager();

我想用以下内容替换它:

@PersistenceContext(unitName = "TT-SpringMVCPU")
private EntityManager _entityManager;

当我尝试时,我收到此错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'showController': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'TT-SpringMVCPU' is defined
    org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:341)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
...

我忘了配置什么?

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:2)

  

我忘了配置什么?

嗯,你没有显示任何内容:)无论如何,Using JPA in Spring without referencing Spring显示了一种做事方式:

  

配置

     
      
  • LocalEnityManagerFactoryBean创建EntityManagerFactory
  •   
  • JpaTransactionManager经理JPA交易
  •   
  • <tx:annotation-driven />告诉Spring寻找@Transactional
  •   
  • 你的bean定义!
  •   
     

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

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" />

    <bean id="productDaoImpl" class="product.ProductDaoImpl"/>

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

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

    <tx:annotation-driven />

</beans>
     

就是这样。两个注释和四个   bean定义。

看看。

另见