我发现这篇文章其中谈到使用Spring作为JPA容器:使用Spring的JPA容器
http://java.sys-con.com/node/366275
我从来没有使用过Spring在此之前,我试图使这项工作,并希望有人能帮我。
在文章中,它声明您需要使用@Transactional注解Spring bean,并使用@PersistenceContext注释方法/域以提供事务支持并注入实体管理器。
是否有定义bean为“Spring Bean”的东西?我有一个bean类上使用泛型实体实现CRUD操作:
@Transactional
public class GenericCrudServiceBean implements GenericCrudService
{
@PersistenceContext(unitName="MyData")
private EntityManager em;
@Override
@PersistenceContext
public <T> T create(T t)
{
em.persist(t);
return t;
}
@Override
@PersistenceContext
public <T> void delete(T t)
{
t = em.merge(t);
em.remove(t);
}
...
...
...
@Override
@PersistenceContext
public List<?> findWithNamedQuery(String queryName)
{
return em.createNamedQuery(queryName).getResultList();
}
}
本来我只是有这个peristence背景注释:
@PersistenceContext(unitName="MyData")
private EntityManager em;
,但有一个空的他们,当被调用findWithNamedQuery。然后我注释了这些方法,但em仍然是空的(没有注入?)。
我想知道这是否与我的bean没有被识别为“Spring”有关。
我已经做了配置,最好的,我可以按照文章中的方向,包括设置在我的context.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:tx="http://www.springframework.org/schema/tx"
tx:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="MyData" />
<property name="dataSource" ref="dataSource" />
<property name="loadTimeWeaver"
class="org.springframework.classloading.ReflectiveLoadTimeWeaver" />
<property name="jpaVendorAdapter" ref="jpaAdapter" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:MySID" />
<property name="username" value="user" />
<property name="password" value="password" />
<property name="initialSize" value="3" />
<property name="maxActive" value="10" />
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform"
value="org.eclipse.persistence.platform.database.OraclePlatform" />
<property name="showSql" value="true" />
</bean>
<bean
class="org.springframework.ormmjpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven />
</beans>
我猜这属于在context.xml文件,因为文章从来没有具体说过哪个文件是“应用程序上下文”文件。如果这是错误的,请让我知道。
与其阅读关于如何在某些网站上做这些东西,你是否阅读过Spring文档? http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa – skaffman 2010-06-09 21:00:11
感谢您的链接。我实际上已经发现/阅读了Spring文档的一部分,但是它没有提供任何关于我的配置可能出错的信息。我对搜索“Spring bean”的搜索过于笼统,搜索不到任何合理的结果。 – sdoca 2010-06-09 22:20:01
您正在使用哪种JPA实现? Spring不是JPA容器,但它与一个(例如Hibernate)集成。 – skaffman 2010-06-10 07:15:04