How can I place the hibernate annotations on the fields, but always have property access?

岁酱吖の 提交于 2019-12-12 03:27:45

问题


I am asking because I would like to use code generation for the getters/setter.

And also because I would prefer the mapping annotations to appear at the top of the class, where I declare the fields.

I wonder if this approach is correct:

@Entity
@Table(name = "test")
// @Access(AccessType.PROPERTY) // cannot use this, because hibernate complains that no 
public class Test implements Serializable
{
  @Id
  // I hope this results in property access for all of the other
  // properties as well, but I am not sure how to confirm this...
  @Access(AccessType.PROPERTY) 
  @Column(name = "id")
  private long                id         = 0;

  @Column(name = "test_string")
  private String              testString = null;

  ...

Update: I just tested the above example and it looks like the 'testString' property is accessed using field access. I added logging statements to the getter/setter and they were never called. On the other hand, when I added @Access(AccessType.PROPERTY) also to the 'testString' field, the getter and setter methods were called.

So at the moment it looks like my only option is to write "@Access(AccessType.PROPERTY)" in front of every field :-(


回答1:


1) Property access isn't the right way to persist entities. You persist state, and state is stored in fields.

2) You can use the @Access annotation to set the access type to use for a class.



来源:https://stackoverflow.com/questions/14915606/how-can-i-place-the-hibernate-annotations-on-the-fields-but-always-have-propert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!