JPA / Hibernate加入恒定价值

时间:2015-03-02 20:04:09

标签: java hibernate jpa

我正在尝试使用join语句中的常量值连接到同一个表中的不同实体。在SQL中,我会做这样的事情......

SELECT *
FROM owner o
JOIN types t on t.owner_id = o.id AND t.type = 'A'
--                                ^^^^^^^^^^^^^^^^ THIS IS WHAT I AM TRYING TO REPLICATE

在Java + JPA / Hibernate中,我试图做这样的事情......

@Entity
@Table(name = "OWNER")
public class Owner {

    @Id
    @Column(name="ID")
    private Long id

    @OneToOne(mappedBy = "owner", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumns({
        @JoinColumn(name = "ID", referencedColumnName = "ID"),
        @JoinColumn(constantValue = "A", referencedColumnName="type")})
    //              ^^^^^^^^^^^^^^^^^^^  I AM LOOKING FOR SOMETHING THAT DOES THIS.
    //                                   constantValue IS NOT A VALID ARGUMENT HERE.
    private TypeA inspectionSnapshot;

    @OneToOne(mappedBy = "owner", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumns({
        @JoinColumn(name = "ID", referencedColumnName = "ID"),
        @JoinColumn(constantValue = "B", referencedColumnName="type")})
    private TypeB inspectionSnapshot;

    /* Getters & Setters ... */
}

@Entity
@Table(name = "TYPES")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING)
public abstract class BaseType {

    @Id
    @OneToOne
    @JoinColumn(name = "OWNER_ID", referencedColumnName="ID")
    private Owner id;

    @Id
    @Column(name = "TYPE")
    private char type

    /* Getters & Setters ... */
}

@Entity
@DiscriminatorValue("A")
public class TypeA extends BaseType {
    /* All functionality in BaseType */
}

@Entity
@DiscriminatorValue("B")
public class TypeA extends BaseType {
    /* All functionality in BaseType */
}

提前致谢!

3 个答案:

答案 0 :(得分:5)

如果您不介意使用特定于Hibernate的注释,可以尝试使用@WhereJoinTable注释,例如:

@OneToOne(mappedBy = "owner", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "ID", referencedColumnName = "ID")
@WhereJoinTable(clause = "TYPE = 'A'")
private TypeA inspectionSnapshot;

请注意,clause属性必须包含SQL,而不是JPQL,因此您需要使用数据库列名而不是JPA实体字段名。

答案 1 :(得分:3)

您正在查看非标准联接。这是处理此类案件的文件:

http://docs.oracle.com/cd/E13189_01/kodo/docs40/full/html/ref_guide_mapping_notes_nonstdjoins.html

希望它有所帮助!

答案 2 :(得分:3)

尝试将常量指定为公式的值

@JoinColumnsOrFormulas({
@JoinColumnOrFormula(formula=@JoinFormula(value="'A'", referencedColumnName="type")),
@JoinColumnOrFormula(column = @JoinColumn("id", referencedColumnName="id"))
})
private TypeA inspectionSnapshot;