是否可以将Spring Data JPA存储库注入到Java持久性实体中? [英] Is it possible to inject spring data jpa repository into java persistent entity?

查看:138
本文介绍了是否可以将Spring Data JPA存储库注入到Java持久性实体中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将spring数据jpa存储库注入到java实体中(使用hibernate将POJO声明为持久性实体)?

Is it possible to inject spring data jpa repository into java entity (using hibernate to declare POJO as persistent entity)?

我有这样的Person java实体模型.

I have Person java entity model like this.

@Entity
@Table(name="PERSON")
public class Person implements Serializable {
    @Id
    @Column(name="PERSON_ID",nullable=false)
    private UUID personId;
    ...

这是spring data jpa存储库:

Here is spring data jpa repository:

public interface PersonRepository extends JpaRepository<Person,UUID> {
    @Query("from Person where Person.id = ?1")
    Person findPersonById(UUID id);

推荐答案

否,您永远不要这样做. JPA实体是在JPA提供程序生命周期内处理的. JPA规范明确禁止在PrePersist,PreUdate等侦听器内执行任何数据库操作.从实体内部进行任何与主动持久性有关的事情,可能会带来意想不到的副作用.

No and you should never do it. JPA entities are handled from within the JPA providers lifecycle. The JPA specification explicitly forbids performing any database operations from within the PrePersist, PreUdate and so on listeners. Doing anything related to active persistence from inside the entity might have unexpected side effects.

关于这个问题是否完全可能.一切皆有可能:)并不意味着它是一个好主意.

About the question if it is possible at all. Everything is possible :) does not mean it is a good idea though.

尽管如此,您将无法控制冬眠或弹簧数据如何初始化这些实体.春季之前,实体是不受管理的,因此,如果您想实际进行某种依赖注入,则需要AspectJ参与执行代码编织.

You will not have control over how hibernate or spring data is initializing those entities though. Entities are not managed by spring so if you want to actually do some dependency injection there you would need AspectJ involved performing code weaving.

这篇关于是否可以将Spring Data JPA存储库注入到Java持久性实体中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆