问题
I hava two entities: PhisicalPerson (PP), JuredicalPerson (JP). And I want to create Phone object. JP has many phones and PP has many phones (one to many relation). So in Phone object I have to create 2 columns for this relations:
class Phone {
@JoinColumn(name="ppId",nullable=true)
@ManyToOne
public PhisicalPerson getPhisicalPerson() {...}
@JoinColumn(name="jpId",nullable=true)
@ManyToOne
public JuredicalPerson getJuredicalPerson() {...}
// number, city code, additional number and other fields
}
Is it right implementation? Or may be it's better to create different entities: PhisicalPersonPhone and JuredicalPersonPhone?
回答1:
That's indeed what you could do, but it looks like you have an inheritance relationship here.
Both PP and JP should probably extend a common base entity Person, and it's the Person entity which should have a list of phones. The Phone entity would then just have one ManyToOne association with Person.
That's assuming that the Phone entity needs to know about its owning person. Maybe a unidirectional association would make more sense here. In this case, using a join table (or two, if you don't want this inheritance relationship), would make more sense.
来源:https://stackoverflow.com/questions/7991830/what-table-structure-to-use-hibernate