开发者

JPA - Multiple columns discriminator

I have 3 tables like this in MySQL 5:

|               PERSON                     |
|  id   |  fullName  | isEmp  |  isParent  |


|      EMPLOYEE        |
|  personId   |  code  |


|       PARENT         |
|  personId   |  job   |

in which, Employee.personId and Parent.personId are foreign keys pointing to Person.id. An employee can also be a parent and vice versa. So how can I config us开发者_开发知识库ing Annotation of JPA 2.0/Hibernate 3? Thanks!


If a Person can be both, you can't solve this through inheritance, because Java doesn't allow multiple inheritance. So you'll have to go with Aggregation, which is confusing on a semantic level, because it's has-a-parent instead of is-a-parent. But I'm afraid it's the way you'll have to go:

@Entity
public class Person{
    @Id
    private Long id;
    @OneToOne(optional=true)
    private Employee employee;
    @OneToOne(optional=true)
    private Parent parent;
    public boolean isParent(){return parent!=null;}
    public boolean isEmployee(){return employee!=null;}
}
@Entity
public class Employee{
    @Id
    private Long id;
    @OneToOne(mappedBy="employee",optional=false)
    private Person person; 
}
@Entity
public class Parent{
    @Id
    private Long id;
    @OneToOne(mappedBy="parent",optional=false)
    private Person person; 
}

(getters / setters etc. omitted)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜