没有检查@Id,确定实体是否是新的 [英] Determine if entity is new without checking @Id
问题描述
有没有一种方法可以确定给定的实体类:
@Entity
class A {
字符串名称;
布尔方法(Object anyEntity){
//如何在这里查看,如果这个实体是全新的
}
新的,我的意思是有人调用了新的A(),甚至可能设置了名字,但从未保存,或者持续存在。
通常可以检查id,但我想要一个不需要id或getId()方法的解决方案。
基本上,即使在分离模式下,该实体也被持久保存到数据库中。
@Version或getVersion也不是一个令人满意的解决方案。
也许是被删除的|| isAttached可能工作,但我不知道如何在Hibernates API上进行调用。
编辑:
另外澄清,我不控制实体,所以我不能添加任何字段给他们。解决方案应该尝试利用底层机制来确定这一点。
经过对Hibernate源代码的一些工作和分析,我相信这是答案:
boolean isNew(T entity){
return((SessionImplementor)session())。getPersistenceContext()。getEntry(entity)== null;
}
另外还有一点需要注意,不用依赖实现就可以获得id as:
boolean hasId(Object entity){
return getId(entity)!= null;
}
Serializable getId(Object entity){
ClassMetadata metadata = metadata(entity);
if(metadata.hasIdentifierProperty()){
return metadata.getIdentifier(entity);
}
返回null;
}
ClassMetadata元数据(对象实体){
return getRepository()。session()。getSessionFactory()。getClassMetadata(entity.getClass());
}
Is there a way to determine given for example entity class:
@Entity
class A {
String name;
}
boolean method(Object anyEntity) {
// How can I check here, if this entity is completely new
}
By new, I mean someone invoked new A() and possibly even set the name, but was never saved, or persisted.
Normally one could check the id, but I want a solution that doest not requires an id, or a getId() method.
Basically, has this entity been persisted to the database, even in detached mode.
@Version or getVersion is also not a satisfactory solution.
Maybe isDetached || isAttached might work, but I am not sure how to make that call on Hibernates API.
EDIT:
Also clarify, I do not control the entities, so I can not add any fields to them. Solution should try to make use of underlying mechanisms to determine this.
After some work and analyzing of Hibernate source code, I believe this is the answer:
boolean isNew(T entity) {
return ((SessionImplementor) session()).getPersistenceContext().getEntry(entity) == null;
}
And on another note, getting the id without relying on an implementation can be done as:
boolean hasId(Object entity) {
return getId(entity) != null;
}
Serializable getId(Object entity) {
ClassMetadata metadata = metadata(entity);
if ( metadata.hasIdentifierProperty() ) {
return metadata.getIdentifier(entity);
}
return null;
}
ClassMetadata metadata(Object entity) {
return getRepository().session().getSessionFactory().getClassMetadata(entity.getClass());
}
这篇关于没有检查@Id,确定实体是否是新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!