Hibernate 大多数是不可变的
我有一个简单的问题Hibernate 大多数是不可变的,hibernate,natural-key,Hibernate,Natural Key,我有一个简单的问题 public class SomeEntity { @Id private Integer id; @NaturalId private User owner; @NaturalId(mutable=true) private String name; ... } 自然id创建了一个唯一的密钥(很好!),它使owner从hibernate中不可变。这也是一件好事,然而,偶尔,管理员需要更换所有者。所以我似乎被迫使它也可变,这真的是讨厌 我可以
public class SomeEntity {
@Id private Integer id;
@NaturalId private User owner;
@NaturalId(mutable=true) private String name;
...
}
自然id创建了一个唯一的密钥(很好!),它使owner
从hibernate中不可变。这也是一件好事,然而,偶尔,管理员需要更换所有者。所以我似乎被迫使它也可变,这真的是讨厌
我可以用一个简单的SQL来克服它,但这意味着说谎,我也不喜欢说谎,因为它会欺骗hibernate做错事
我正在寻找一种干净的方式来表达类似“除非我说不可变”(尽管我对这种可能性持悲观态度)。我也很好奇,替代品的缺点是什么。在我的竞争中:这种情况表明所有者和名称不再是自然ID。它们只是属性,服务级别的属性可以随时更改,从业务级别的角度来看,拥有唯一的
owner、name
值对是有限制的。因此,“不可变,除非我说”的情况应该在“业务”-服务级别上解决:即所有者变为可变的,并且在您的服务内部您正在创建单独的方法来修改它,其他方法不应该修改此属性。i、 e:
@Secured(ADMIN_ONLY_ACCESS)
public SomeEntity modifyAdministrative(SomeEntity entity) {
//here you allow to modify owner
}
public SomeEntity modify(SomeEntity entity) {
// here owner should be used as readonly property
// and you can controll this only on your own,
// hibernate is not able to support you anymore with immutability control
}
或者,您可以将某些实体表的数据映射到第二个不同的实体,并重用hibernate提供的NaturalId
行为,即
public class SomeEntity {
// Keep this for general usage
@Id private Integer id;
@NaturalId private User owner;
@NaturalId(mutable=true) private String name;
...
}
public class SomeEntityForAdmin {
// use this for administrative usage
@Id private Integer id;
private User owner;
private String name;
...
}
SomeEntityForAdmin
仅用于需要更改所有者的管理情况。其余的代码都保持原样
但请注意:缓存会有复杂的问题(一旦发生sometentityforadmin
或sometentity
的更改,您必须为缓存创建适当的失效策略),当在同一事务中同时涉及SomeEntity
和SomeEntityForAdmin
时,它就会变得一团糟