63

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..

4

5 回答 5

81

正如其他人所提到的,如果您注释属性 getter 方法,那么 Hibernate 在从数据库读取值时会使用 setter。基本上,Hibernate 假定它写入数据库的任何内容最终都需要从数据库中读取。这意味着如果您注释了一个 getter,那么它在从数据库中读取对象时需要调用一个 setter。

您可以将 setter 设为私有(Hibernate 将使用反射来访问 setter)。这是在仍然使用 Hibernate 进行关系映射的同时保留类合同的好方法。

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

于 2010-04-20T17:28:44.763 回答
12

您应该使用 注释您的类@Entity(access = AccessType.FIELD)并注释您的属性。这应该可以解决您的问题。setter 是支持重构的最佳方式。那里有小二传手有什么问题。

于 2010-04-20T16:19:05.783 回答
10

access="field"如果您不想使用设置器,请设置:

<class name="com.demo.hibernate.Country" table="country">
  <id name="countryId" column="id" type="int">
    <generator class="increment" />
  </id>
  <property name="name" column="name" access="field" type="string" />
  <property name="countryCode" column="country_code" access="field" type="string" />
</class>
于 2014-12-01T21:11:42.913 回答
1

Hibernate 使用set方法来初始化您从数据库中读取的实体。

也许,如果您对实体字段进行访问修饰符,或者defaultHibernate将直接初始化字段而不使用 setter(我读过一些关于它的内容,但我不确定它是否有效)。但是使用 setter 是更受欢迎的方式。protectedpublic

于 2010-04-20T16:12:59.103 回答
-1

如果您不使用 setter 并使用私有属性,Hibernate 将不得不通过反射检索字段并执行 field.setAccessible(true)。我不认为 Hibernate 这样做。

我真的不知道我们是否可以告诉 Hibernate 这样做,但据我记得,默认配置正在使用 setter... 将 log/sysout 放在 set 上,您会看到它使用 setter。

于 2010-04-20T16:23:11.920 回答