简体   繁体   English

给定一个Java对象,我可以通过休眠确认它的bean是否可持久

[英]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. 我敢肯定,在运行时,您可以使用某种jedi-reflection-trick来找出您的实体是Hibernate实体的天气(我不建议这样做),但是,在通常情况下,您不必担心它的不是休眠实体, Session.saveOrUpdate()方法将引发HibernateException解释其无法保存和/或更新它的原因。

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. 您可以做的是记录您的API,以了解它期望的实体类型以及如果传递了一些不同的东西而导致的行为。

There are a few methods on the Session interface which take a Class argument, like createCriteria(Class) and getCurrentLockMode(Class) . Session接口上有一些采用Class参数的方法,例如createCriteria(Class)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) . 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; 从JavaDoc 返回:与给定实体关联的元数据; may be null if no such entity was mapped. 如果未映射任何此类实体,则可以为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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