我正在使用Hibernate加入继承(1个根表和2个子表)。例如:
enti
)pers
)和公司(comp
)人员和公司都有字段email
,但由于遗留原因,我无法统一根类实体中的email
字段。映射看起来像这样:
@Entity
@Table(name = "enti")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "discriminator", discriminatorType = DiscriminatorType.STRING)
class Entity {
// ...
}
@Entity
@Table(name = "pers")
@PrimaryKeyJoinColumn(name = "id")
@XmlRootElement
@DiscriminatorValue(value = "discriminator_pers")
@Indexed
class Person {
@Column(name = "email")
private String email; // getter + setter
}
@Entity
@Table(name = "comp")
@PrimaryKeyJoinColumn(name = "id")
@XmlRootElement
@DiscriminatorValue(value = "discriminator_comp")
@Indexed
class Company {
@Column(name = "email")
private String email; // getter + setter
}
在email
字段中使用hibernate条件API时,hibernate只能映射到它可以找到的第一个字段,即comp
电子邮件字段。
Criteria criteria = session.createCriteria(Entity.class)
.add(Restrictions.eq("email", "email@email.com"));
生成的SQL如下所示:
select ...
from enti this_
left outer join comp this_1_ on this_.id = this_1_.id
left outer join pers this_2_ on this_.id = this_2_.id
where this_1_.email = ?
一种解决方案是:在每个实体中将comp.email
映射到companyEmail
和pers.email
到personEmail
,但这意味着需要进行大量的重构。
是否可以在两个子类中使用相同的字段名称,并在两个表上进行休眠搜索?