Does Hibernate have an API for reading the value of an entity's identity field? In my case, this would be the Serializable
value returned by the field annotated with @Id
. For example, suppose I had a Person
entity:
class Person {
@Id private long id;
// ... other fields, getters/setters, etc ...
}
Person p = new Person();
p.setId(42L);
Hibernate.unknownFunction(p); // r开发者_如何学Ceturns 42L
Sure I could read the annotations to find the @Id
field myself, but this seems like something that might be built in.
session.getIdentifier(object)
Return the identifier value of the given entity as associated with this session. An exception is thrown if the given entity instance is transient or detached in relation to this session.
The object needs to have an ID, and to be associated with the current session, otherwise an exception is thrown. But that is logical, I think.
Well, if you need a method that return id in arbitrary classes, design a interface to satisfy this. for example:
public interface IdHolder {
Integer getId();
}
With such interface, you could make some utility methods to retrive id from arbitrary classes.
The cglib is a robust but a bit of tricky way to do it.
I can't say 100% no - but I really doubt it since not all Entities are annotated with @Id
; there are other variants that can be used such as @EmbeddedId
. Given this, can't you just use reflection to get at your id value?
精彩评论