Tuesday, November 2, 2010

Hibernate mapping cheat sheet

Check list

1. Make sure Collections are initialized.
2. Make sure Collections can't be null.
3. Most names and some other fields should not be null.

@Entity
@Table(name = "ar_campus")
public class Campus . . .

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    @Column(name = "xxx")
    @Column(name = "xxx", length = 11, unique = true, nullable = false)
    String someColumn;

Join column name has this rule: "Single same name as property, set name of parent"

Child NO reference back to parent.

class Hand {
    @OneToMany
    @JoinColumn(name = "handid")
    Set<Finger> fingers;

Child HAS reference back to parent.

class Hand {
    @OneToMany(mappedBy = "hand")
    Set<Finger> fingers;
  
class Finger {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "handid")
    Hand hand;

One to one with join column:

class Organization {
    @OneToOne(optional = false, mappedBy = "organization")
    OrgBoardInfo boardInfo;

class BoardInfo {
    @OneToOne(optional = false)
    @JoinColumn(name = "orgid", unique = true, nullable = false, updatable = false)
    Organization organization;

One to one with shared key:

class User {
    @OneToOne()
    @PrimaryKeyJoinColumn
    public AuxInfo auxInfo;

class AuxInfo {
    //(note must NOT put @GeneratedValue annotation on id)
    @Id
    Long    id;

    @OneToOne()
    @PrimaryKeyJoinColumn
    User    user;

Built in Java classes (String, Date, Long) or custom element.

class Board {
    @Enumerated(EnumType.STRING)
    @Column(name = "type")
    public BoardType type;

class Campus {
    @Column(name = "holiday", nullable = false)
    @CollectionOfElements(targetElement = PersistentLocalDate.class)
    @JoinTable(name = "ar_campus_holiday", joinColumns = { @JoinColumn(name = "cid") })
    Set<LocalDate> holidays;

class User {
    @Column(name = "system", nullable = false)
    @CollectionOfElements
    @Enumerated(EnumType.STRING)
    @JoinTable(name = "user_desired_system", joinColumns = @JoinColumn(name = "user"))
    Set<ExternalSystem> desiredSystems;

class Reservation {
    @ManyToMany
    @JoinTable(name = "rez_sr", joinColumns = { @JoinColumn(name = "rezId") }, inverseJoinColumns = { @JoinColumn(name = "srId") })
    Set<SubReceipt> subReceipts;

Column specs (for postgresql)

    @Column(name = "yearsOfExperience", nullable = false, columnDefinition = "integer default 0")
    int            yearsOfExperience;

    @Column(name = "experience", nullable = false, columnDefinition = "character varying(5000) default ''")
    String        experience;

    @Column(name = "deleted", nullable = false, columnDefinition = "bool default false")
    boolean deleted;

    @Column(name = "reservationId", nullable = false, columnDefinition = "bigint default 0")
    long reservationId;

No comments:

Post a Comment