How do I fetch entity informations depends on a field value ?
@Entity
@Table(name = "transaction")
@Getter
@Setter
@ToString(callSuper = true)
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "src_type")
private Long sourceType;
@Column(name = "src_id")
private Long sourceId;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "src_id", insertable = false, updatable = false)
private Company company;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "src_id", insertable = false, updatable = false)
private User user;
}
I would like to fetch Company information with sourceId value of Tranaction entity when sourceType's value is "COMPANY" and User information with sourceId value of Tranaction entity when sourceType's value is "USER".
How can I achieve it with JPA or Hibernate annotations ?
For an example : a transaction record with ID '1' has sourceType = 'USER' and sourceId = 1 , then I would like to fetch User value from user table with related id = 1 but I don't want to join and fetch Company value from company table with id = 1 because sourceType's value is not 'Company'.
I've also tried with below annotations like
// @SQLRestriction("sourceType = 'COMPANY'")
// @SQLJoinTableRestriction("sourceType = 'COMPANY'")
// @JoinColumnsOrFormulas({@JoinColumnOrFormula(formula = @JoinFormula(value = "sourceType = 'COMPANY'", referencedColumnName = "sourceId"))})
// @JoinFormula(value = "sourceType = 'COMPANY'", referencedColumnName = "sourceId")
but didn't worked as I expected.
Try this:
Note: In my case @OneToOne causes error, I suppose because with the formula Hibernate cannot be sure that the association is unique.