2020-04-20

Hibernate JPA @SecondaryTable Example

@SecondaryTable

The @SecondaryTable annotation is used to specify a secondary table for the currently annotated entity.

SecondaryTable Specifies a secondary table for the annotated entity class. Specifying one or more secondary tables indicates that the data for the entity class is stored across multiple tables.
If no SecondaryTable annotation is specified, it is assumed that all persistent fields or properties of the entity are mapped to the primary table. If no primary key join columns are specified, the join columns are assumed to reference the primary key columns of the primary table, and have the same names and types as the referenced primary key columns of the primary table.

    Example 1: Single secondary table with a single primary key column.

    @Entity
    @Table(name="CUSTOMER")
    @SecondaryTable(name="CUST_DETAIL",
        pkJoinColumns=@PrimaryKeyJoinColumn(name="CUST_ID"))
    public class Customer { ... }


    Example 2: Single secondary table with multiple primary key columns.

    @Entity
    @Table(name="CUSTOMER")
    @SecondaryTable(name="CUST_DETAIL",
        pkJoinColumns={
            @PrimaryKeyJoinColumn(name="CUST_ID"),
            @PrimaryKeyJoinColumn(name="CUST_TYPE")})
    public class Customer { ... }


Overriding SQL statements for secondary tables

@Entity(name = "Person")
@Table(name = "person")
@SQLInsert(
    sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) "
)
@SQLDelete(
    sql = "UPDATE person SET valid = false WHERE id = ? "
)
@SecondaryTable(name = "person_details",
    pkJoinColumns = @PrimaryKeyJoinColumn(name = "person_id"))
@org.hibernate.annotations.Table(
    appliesTo = "person_details",
    sqlInsert = @SQLInsert(
        sql = "INSERT INTO person_details (image, person_id, valid) VALUES (?, ?, true) ",
        check = ResultCheckStyle.COUNT
    ),
    sqlDelete = @SQLDelete(
        sql = "UPDATE person_details SET valid = false WHERE person_id = ? "
    )
)
@Loader(namedQuery = "find_valid_person")
@NamedNativeQueries({
    @NamedNativeQuery(
        name = "find_valid_person",
        query = "SELECT " +
                "    p.id, " +
                "    p.name, " +
                "    pd.image  " +
                "FROM person p  " +
                "LEFT OUTER JOIN person_details pd ON p.id = pd.person_id  " +
                "WHERE p.id = ? AND p.valid = true AND pd.valid = true",
        resultClass = Person.class
    )
})
public static class Person {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @Column(name = "image", table = "person_details")
    private byte[] image;

    //Getters and setters are omitted for brevity

}

No comments:

Post a Comment