2020-06-20

Hibernate JPA @JoinColumnOrFormula Example

@JoinColumnOrFormula

The @JoinColumnOrFormula annotation is used to specify that the entity association is resolved either through a FOREIGN KEY join (e.g. @JoinColumn) or using the result of a given SQL formula (e.g. @JoinFormula).

JoinColumnOrFormula Allows joins based on column or a formula. One of formula() or column() should be specified, but not both.

@JoinColumnOrFormula mapping

The @JoinColumnOrFormula annotation is used to customize the join between a child Foreign Key and a parent row Primary Key when we need to take into consideration a column value as well as a @JoinFormula.

Example : @JoinColumnOrFormula mapping usage

@Entity(name = "User")
@Table(name = "users")
public static class User {

@Id
private Long id;

private String firstName;

private String lastName;

private String language;

@ManyToOne
@JoinColumnOrFormula( column =
@JoinColumn(
name = "language",
referencedColumnName = "primaryLanguage",
insertable = false,
updatable = false
)
)
@JoinColumnOrFormula( formula =
@JoinFormula(
value = "true",
referencedColumnName = "is_default"
)
)
private Country country;

//Getters and setters omitted for brevity

}

@Entity(name = "Country")
@Table(name = "countries")
public static class Country implements Serializable {

@Id
private Integer id;

private String name;

private String primaryLanguage;

@Column(name = "is_default")
private boolean _default;

//Getters and setters, equals and hashCode methods omitted for brevity

}

No comments:

Post a Comment