开发者

The difference between annotating fields and methods in JPA (Hibernate)?

Are there any statements in JPA spec or official docs about certain JPA implementations which describe the behavior when we annotate entity's methods and when we annotate entity's fields?

Just a few hours ago I met an ugly problem: I use JPA (via Hibernate, but without anything Hybernate-specific in java code) with MS SQL Server. And I put all annotations on entities' fields (I preferred this style until this day).

When I looked at the DB I found that all table columns which should be foreing keys and which should contain some integers (ids) in fact had varbinary(255, null) type a开发者_JAVA百科nd contained hashes of something (I don't know what was that but it looked as a typical MD5 hash).

The most frustrated thing is that the app worked correctly. But occasionally (on updates) I got MS SQL exception which stated that I tried to insert too long values and data cannot be truncated.

Eventually (as an experiment) I removed all annotations from entities fields and put all of them on methods. I recreated DB and all tables contained perfect FK column. And those columns stored integers (ids, like 1, 3 ,4 ...).

So, can somebody explain what was that?

I've found this SO thread and it's accepted answer says that the preferred way is to put annotations on fields. At least for my concrete case I can say that it's not true.


JPA allows for two types of access to the data of a persistent class. Field access which means that it maps the instance variables (fields) to columns in the database and Property access which means that is uses the getters to determine the property names that will be mapped to the db. What access type it will be used is decided by where you put the @Id annotation (on the id field or the getId() method).


From experience, I do the following.

  1. I put the entity details at the top of the entity class definition, (schema, row constraints, etc) for instance....

    @Entity
    @Table(name="MY_TABLE", schema = "MY_SCHEMA", uniqueConstraints = @UniqueConstraint(columnNames = "CONSTRAINT1"))
    
  2. For the fields defined, I do not put the annotations on the field declarations, but rather on the getter methods for those fields

    @Column(name = "MY_COL", table="MY_TABLE", nullable = false, length = 35)
    public String getMyCol() {
        return this.myCol;
    }
    
    public void setMyCol(String myCol) {
        this.myCol = myCol;
    }
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜