获取子实体中的公共字段

时间:2016-03-24 11:51:18

标签: java hibernate jpa

我有一些实体设置如下:

@Entity
@Table(name = "TABLE_A")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class A {

    @ManyToOne(targetEntity = I.class, optional = true, fetch = FetchType.LAZY)
    private I i;
}

@Entity
@Table(name = "TABLE_I")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class I {

    // Common fields for all I here
}

@Entity
@Table(name = "TABLE_IM")
@Inheritance(strategy = InheritanceType.JOINED)
public class IM extends I {

    @ManyToOne(targetEntity = S.class, optional = true, fetch = FetchType.LAZY)
    private S s;
}

@Entity
@Table(name = "TABLE_IS")
@Inheritance(strategy = InheritanceType.JOINED)
public class IS extends I {

    @ManyToOne(targetEntity = S.class, optional = true, fetch = FetchType.LAZY)
    private S s;
}

@Entity
@Table(name = "TABLE_IA")
@Inheritance(strategy = InheritanceType.JOINED)
public class IM extends I {

    // In this and any subsequent implementations of I, there is no S
}

@Entity
@Table(name = "TABLE_S")
@Inheritance(strategy = InheritanceType.JOINED)
public class S extends I {

    @Column
    private Long x = 0L;
}

所以类 I 可以有多个实现,但只有2个具有列 S 。现在我正在尝试编写一个从TABLE_IMTABLE_IS获取 S 的查询,哪个包含它完全无关紧要。这是我的查询:

select s from A a 
 join a.i i 
 left join i.s s -- Just FYI: If this is not specifically defined as a left join, it would do an inner join instead

但是在JPA中执行时它不会返回任何内容,因为TABLE_IM中没有任何内容,而TABLE_IS确实包含一些记录,JPA执行的查询似乎是这样的:< / p>

select s.id from TABLE_A   a 
 left outer join TABLE_I   i on i.id = a.i_id
 left outer join TABLE_IM im on im.id = i.id
 left outer join TABLE_IS is on is.id = i.id
 left outer join TABLE_IA ia on ia.id = i.id
 -- It keeps adding left joins for every implementation of the abstract I
 left outer join TABLE_S   s on im.s_id = s.id

我认为JPA的多态行为也会加入TABLE_STABLE_IS,但它可能不是递归的,所以它没有,因此没有返回任何记录。这适用于本机查询,但首选JPA。有没有办法在不为 IM IS 创建另一个抽象层或在其中一个类中重命名字段 S 的情况下执行此操作?

谢谢!

0 个答案:

没有答案