假设有一个类似Document
的实体,并且它有type
字段。当type
为draft
时,可以更新。但是当type
为created
时,hibernate不应该使用任何修改后的值保存文档。是否可以使用hibernate?
答案 0 :(得分:3)
您可以使用@Immutable
注释创建一个不可变实体,在这种情况下,您无法修改实体,然后它会保持不变。
另一个解决方案是通过会话将实体设为只读,如official documentation中所示。
另一个解决方案是为您的实体提供EntityListener
,例如:
@Entity
@EntityListeners(MakeReadOnly.class)
public class SomeEntity {
// ...
}
public class MakeReadOnly {
@PreUpdate
void onPreUpdate(Object o) {
//according to filed value throw new RuntimeException("...");
}
}