2020-04-21

Hibernate JPA @Table Example

@Table

The @Table annotation is used to specify the primary table of the currently annotated entity.

Table Specifies the primary table for the annotated entity. Additional tables may be specified using SecondaryTable or SecondaryTables annotation.
If no Table annotation is specified for an entity class, the default values apply.

    Example:

    @Entity
    @Table(name="CUST", schema="RECORDS")
    public class Customer { ... }


Example:

@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