Mau*_*ari 14 spring-data spring-data-jpa
我正在为Spring Data JPA存储库编写自定义实现.所以我有:
MyEntityRepositoryCustom =>与自定义方法的接口MyEntityRepositoryUmpl =>执行上面的接口MyEntityRepository=>标准接口,扩展JpaRepository和MyEntityRepositoryCustom我的问题是:在MyEntityRepositoryUmpl我需要访问注入Spring Data的实体管理器的实现中.怎么弄?我可以使用@PersistenceContext它来自动装配,但问题是此存储库必须在设置多个持久性单元的应用程序中工作.所以,要告诉Spring我需要哪一个,我将不得不使用@PersistenceContext(unitName="myUnit").但是,由于我的存储库是在可重用的服务层中定义的,因此我无法知道更高级别的应用程序层将配置为注入我的存储库的持久性单元的名称.
换句话说,我需要做的是访问Spring Data本身正在使用的实体管理器,但是在查看Spring Data JPA文档(不那么快)后,我找不到任何相关内容.
老实说,这些Impl类完全没有意识到Spring Data,尽管在Spring Data手册中被描述为一个优势,但实际上每当你需要访问通常由Spring Data本身在自定义实现中提供的东西时(实际上,我会说...).
Ale*_*toy 22
从Spring Data JPA 1.9.2版本开始,您可以通过JpaContext访问EntityManager,请参阅:http://docs.spring.io/spring-data/jpa/docs/1.9.2.RELEASE/reference/html/#jpa.misc .jpa-context.例:
@Component
public class RepositoryUtil
{
@Autowired
private JpaContext jpaContext;
public void deatach(T entity)
{
jpaContext.getEntityManagerByManagedType(entity.getClass()).detach(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
PS 如果某个类有多个EntityManager候选者,则此方法不起作用,请参阅JpaContext#getEntityManagerByManagedType - > DefaultJpaContext#getEntityManagerByManagedType的实现.
我能找到的最好的办法是建立一个“约定”:我的存储库声明他们希望有一个名为的持久性单元myConventionalPU可用。然后,应用程序层将该别名分配给它设置并注入 Spring Data 的实体管理器工厂,因此我的自定义实现可以通过使用该别名通过自动装配接收正确的 EMF。这是我的应用程序上下文的摘录:
<bean id="myEntityManagerFactory" name="myConventionalPU"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
[...]
</bean>
<jpa:repositories base-package="com.example"
entity-manager-factory-ref="myEntityManagerFactory"
transaction-manager-ref="transactionManager" />
Run Code Online (Sandbox Code Playgroud)
在我的自定义实现中:
@PersistenceContext(unitName = "myConventionalPU")
private EntityManager em;
Run Code Online (Sandbox Code Playgroud)
我带着这个要求打开了DATAJPA-669。
| 归档时间: |
|
| 查看次数: |
27002 次 |
| 最近记录: |