2015-03-02 85 views
4

我想在join語句中使用常量值從同一表中加入不同的實體。在SQL中,我會做這樣的事情...JPA /休眠加入常量值

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

如果你不介意使用Hibernate的相關注釋,你可以用@WhereJoinTable註釋嘗試,如:

​​

注意,clause屬性必須包含SQL,而不是JPQL,所以你需要使用數據庫列名稱而不是JPA實體字段名稱。