简体   繁体   中英

Given a java object can I confirm its a bean persist-able by hibernate

有时候,我想传递一个对象来说一个审计层,其唯一的工作就是保留实体(无论是哪种类型),但是由于这是一个公共API,因此我想确定传递的对象是一个休眠实体Bean,然后仅尝试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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM