简体   繁体   中英

How to annotate composition of abstract class instance?

I have a design of Person as shown in the following picture. The design is to allow a person to change his role from Staff to Student , Student to Faculty and so on.

I want to persist this system to DB using hibernate annotation. Does anyone know how to do that?

Thanks a lot!

在此处输入图片说明

So you have 1:N relation between Entity Persona and abstract entity Person Role. Think this may work for you.

@Entity
public class Person {
  // Here you have all roles in some collection.
  @OneToMany(mappedBy="person", fetch=FetchType.LAZY)
  private List<PersonRole> roles;
  ...
}

@Entity
public abstract class PersonRole {
    @ManyToOne
    @JoinColumn(name="PERSON_ID")
    private Person person;
    ...
}

@Entity
public class Staff extends PersonRole {
   ...
}

Also don't forget to set proper

@Inheritance(strategy=InheritanceType.<strategy>)

to define how class model is mapped to relational model.

Edit: Unfortunately @MappedSuperclass can't be used in relations mapping so this is not an option here as long as you would like to have PersonRole collection in Person entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM