java 使用 Hibernate 时@Immutable 和@Entity(mutable=false) 有什么不同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1590422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:11:53  来源:igfitidea点击:

What is the different between @Immutable and @Entity(mutable=false) when using Hibernate

javahibernatejpaentityimmutability

提问by non sequitor

What is the difference between the two if any?

如果有的话,两者有什么区别?

Should one or both be used on an entity?

应该对一个实体使用一个还是两个?

回答by ChssPly76

For entitythere's practically no difference. @Immutablegets priority (that is if you have entity that's annotated both as @Immutableand @Entity(mutable = "true")it is going to be treated as immutable).

对于实体,几乎没有区别。@Immutable获得优先权(也就是说,如果您的实体同时被注释为 as@Immutable并且@Entity(mutable = "true")它将被视为不可变的)。

@Immutablecan also be used on collections with pretty much the same semantics. Details are here

@Immutable也可以用于具有几乎相同语义的集合。详情在这里

回答by Vlad Mihalcea

The org.hibernate.annotations.Entityannotation is deprecated and will be removed in a future release of Hibernate.

org.hibernate.annotations.Entity注释已被弃用,并将在 Hibernate 的未来版本中删除。

Hence, you should always use the @Immutabaleannotation if you have entities that should never be modified by Hibernate.

因此,@Immutabale如果您有不应被 Hibernate 修改的实体,则应始终使用注释。

As I explained in this article, the @Immutableannotation tells Hibernate to load entities in read-only mode, hence entity modifications cannot be tracked by the dirty checking mechanism.

正如我在本文中所解释的,@Immutable注释告诉 Hibernate 以只读模式加载实体,因此脏检查机制无法跟踪实体修改。

However, the @Immutableentities can still be updated via JPQL or Criteria API bulk update queries.

但是,@Immutable实体仍然可以通过 JPQL 或Criteria API 批量更新查询进行更新

To make sure @Immutabaleentities are never modified for bulk update queries, from Hibernate 5.2.17 onwards, you can set the following configuration property:

为了确保@Immutabale永远不会为批量更新查询修改实体,从 Hibernate 5.2.17 开始,您可以设置以下配置属性:

<property
    name="hibernate.query.immutable_entity_update_query_handling_mode"
    value="exception"
/>

With this property in place, a bulk update query will end up throwing an exception and the entity update will be prevented.

有了这个属性,批量更新查询最终会抛出异常,实体更新将被阻止。