有一个getter时,Hibernate是否总是需要一个setter? [英] Does Hibernate always need a setter when there is a getter?

查看:78
本文介绍了有一个getter时,Hibernate是否总是需要一个setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们用 @Column @Basic 来注释一些Hibernate getter方法。



如果我们没有相应的setter,我们会得到一个异常。为什么是这样?

在我们的例子中,我们得到了从getter返回的值(存储在数据库中),setter没有功能。所以我们只是有一个空方法来解决错误条件。正如其他人所提到的,如果你注释一个属性getter方法,那么Hibernate在从数据库读取值时使用setter。基本上,Hibernate假定它写入数据库的任何内容最终都需要从数据库中读取。这意味着如果你注释一个getter,那么当从数据库读取对象时它需要调用setter。

访问setter)。这是保持你的类的合同,同时仍然使用Hibernate进行关系映射的好方法。



如果字段是从类中的其他属性派生的,那么为什么你将它存储在数据库中?您可以使用 @Transient 注释来标记它不应该存储在数据库中的字段。您甚至可以使用 @Formula 注释让Hibernate为你导出字段(它通过使用查询中的公式来发送给数据库)。


We have some Hibernate getter methods annotated with both @Column and @Basic.

We get an exception if we don't have the corresponding setter. Why is this?

In our case we are deriving the value returned from the getter (to get stored in the DB) and the setter has no functional purpose. So we just have an empty method to get around the error condition..

解决方案

As others have mentioned, if you annotate a property getter method, then Hibernate uses the setter when reading values from the database. Basically, Hibernate assumes that anything that it is writing to the database will eventually need to be read from the database. This implies that if you annotate a getter, then it needs to call a setter when reading the object from the database.

You can make the setter private (Hibernate will use reflection to access the setter). This is great way to preserve the contract of your class while still using Hibernate for relational mapping.

If the field is derived from other properties in the class, then why are you storing it in the database? You can use the @Transient annotation to mark the field that it shouldn't be stored in the database. You can even use the @Formula annotation to have Hibernate derive the field for you (it does this by using the formula in the query it sends to the database).

这篇关于有一个getter时,Hibernate是否总是需要一个setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆