【问题标题】:Object/Entity lifecycles when using spring-data-jpa with hibernate as jpa provider?将spring-data-jpa与hibernate用作jpa提供程序时的对象/实体生命周期?
【发布时间】:2020-12-12 06:05:57
【问题描述】:

当使用 spring-data-jpa 和 hibernate 作为 jpa 提供者时,对象/实体生命周期是否与直接使用 hibernate 或由 hibernate 定义(或者可能是 jpa 规范本身)时相同。

Hibernate 将这些生命周期定义为实体 - Transient, Persistent, Detached, Removed。 这些相同的生命周期在使用 spring-data-jpa 时是否也适用。 如果是这样,下面 Hibernate 提供的方法如何与 spring jpa crud 存储库的方法映射。

//below methods in hibernate move an entity to persistent state
save(e), 
persist(e);  
update(e);  
saveOrUpdate(e);  
lock(e);  
merge(e);  

//below methods in hibernate move an entity to detached state
detach(e);  
evict(e);  

【问题讨论】:

    标签: spring-boot hibernate jpa spring-data-jpa


    【解决方案1】:

    对于问题的第一部分:

    Spring Data JPA 只是在 JPA 之上提供了一些舒适的机制。 持久性、映射和生命周期仍然由 JPA 或其实现管理,即在您的情况下是 Hibernate。 这意味着生命周期是相同的。

    Spring Data JPAs方法与Hibernates/JPA方法的映射见下表。

    Spring Data JPA
    CrudRepository.save* for new entities EntityManager.persist, EntityManager.merge otherwise
    CrudRepository.delete* EntityManager.remove
    CrudRepository.findById EntityManager.find*
    JpaRepository.*flush EntityManager.flush
    JpaRepository.getById EntityManager.getReference

    在接口中预定义的其他查询方法或以其他方式使用各种类型的查询。

    【讨论】:

    • spring数据jpa到jpa的良好映射。 +1。如果你喜欢 Q,你可以点赞它,这样它也可以帮助其他人。
    【解决方案2】:

    Spring Data Jpa 只是一个抽象层,不提供生命周期管理。因此,如果您使用 hibernate 作为 jpa 实现您的对象的生命周期将根据 hibernate 的生命周期管理进行调节

    此外,您还可以找到一些其他解释herehere

    【讨论】:

    • 很好的参考资料。 +1。如果你喜欢 Q 可以点赞。
    猜你喜欢
    • 1970-01-01
    • 2014-08-05
    • 2014-01-25
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2019-07-20
    相关资源
    最近更新 更多