there are times when I want to pass in an object to say an Auditing layer whose sole job is to persist the entities (no matter what type) , but since this is a public API, I want to ascertain that the passed in object is a hibernate entity bean and then only try the saveOrUpdate()
I'm sure that at runtime you could use some sort of jedi-reflection-trick to find out weather your entity is a Hibernate entity (An approach I would not recommend), however, under normal circumstances, you dont have to worry if its not a hibernate entity, the Session.saveOrUpdate()
method will throw an HibernateException
explaining the reason why it couldn't save and/or update it.
There is nothing you can do to prevent your public method from being called with an arbitrary object type. What you can do is document your API as to what type of entities it does expect and the resulting behavior if something different is passed to it.
There are a few methods on the Session
interface which take a Class
argument, like createCriteria(Class)
and getCurrentLockMode(Class)
. I haven't tried this, but you could try passing the class of your object to one of those methods. If you're lucky, then if it's not an entity class, then an exception will be thrown.
Not elegant, but it's all I got :)
http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/SessionFactory.html#getClassMetadata(java.lang.Class). From JavaDoc, Returns: The metadata associated with the given entity; may be null if no such entity was mapped.