Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate Join On Constant Value

I am trying to join to different entities from the same table using a constant value in the join statement. In SQL, I would do something like this...

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

In Java + JPA/Hibernate, I am trying to do something like this...

@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 */
}

Thanks in advance!

like image 970
EvilJoe Avatar asked Mar 02 '15 20:03

EvilJoe


1 Answers

Try to specify a constant as the value of the formula

@JoinColumnsOrFormulas({
@JoinColumnOrFormula(formula=@JoinFormula(value="'A'", referencedColumnName="type")),
@JoinColumnOrFormula(column = @JoinColumn("id", referencedColumnName="id"))
})
private TypeA inspectionSnapshot;
like image 126
Dmitry Avatar answered Sep 27 '22 21:09

Dmitry