Can I annotate a member inherited from a superclass?

前端 未结 4 685
一向
一向 2021-02-13 20:02

If I have a class such as:

class Person {
  private String name;
  ...constructor, getters, setters, equals, hashcode, tostring...
}

Can I subc

4条回答
  •  借酒劲吻你
    2021-02-13 20:34

    Late answer, but I think overriding the getter method is a solid approach.

    This can be a superclass for all tables which has an id field. If you serialize this object into JSON the id will always appear.

    @MappedSuperclass
    class ModelEntity {
    
        @Id
        @Column(
            name      = "id",
            updatable = false,
            nullable  = false
        )
        @GeneratedValue(strategy=GenerationType.AUTO)
        public Long id
    }
    

    But let's say you have the following objects (tables) Person and Occupation where Person has a one to many relationship with Occupation.

    @Entity
    @Table(name = "occupation")
    Occupation extends ModelEntity {
    
        @Column
        String company
    
        @Column 
        String position
    }
    
    @Entity
    @Table(name = "person")
    Person extends ModelEntity {
    
        @Column
        String name
    
        @OneToMany
        Occupation occupation
    }
    

    Provided that id is present in all of the classes that extend ModelEntity if you were to serialize a Person object, you would get something like:

    {
        "id" : 1,
        "name" : "Jordan",
    
        "occupation" : {
            "id" : 1,
            "company" : "WalMart",
            "position" : "Engineer"
        }
    
    }
    

    If you did not want the id to show up in the Occupation object, but you did want it to show up in the Person object, you can implement a getId() method at the Occupation class level, and apply desired annotations:

    @Transient
    public Long getId() {
    
        return id;   
    }
    

    Now your JSON would appear as follows: even though they both have an id column in the actual database:

    {
        "id" : 1,
        "name" : "Jordan",
    
        "occupation" : {
            "company" : "WalMart",
            "position" : "Engineer"
        }
    
    }
    

提交回复
热议问题