Skip to content

Instantly share code, notes, and snippets.

@bekce
Last active October 17, 2015 16:20
Show Gist options
  • Select an option

  • Save bekce/40dbff8b691fb583b3df to your computer and use it in GitHub Desktop.

Select an option

Save bekce/40dbff8b691fb583b3df to your computer and use it in GitHub Desktop.
JPA concise examples

JPA concise examples

One to one

class Customer
  @OneToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="address_fk",nullable=false)
  Address address;

One to many with explicit join table

class Order
  @Temporal(TIMESTAMP)
  Date orderDate;
  @OneToMany
  @JoinTable(name="jnd_ord_line",
    joinColumns=@JoinColumn(name="order_fk")
    inverseJoinColumns=@JoinColumn(name="order_line_fk"))
  List<OrderLine> orderLines;

One to many with join column

class Order 
  @OneToMany(fetch=EAGER)
  @JoinColumn(name="order_fk") 
  List<OrderLine> orderLines;

Creates foreign key on OrderLine named order_fk.

This is the inverse of @ManyToOne on OrderLine, but their results are the same on database level. If you use @ManyToOne on OrderLine, use mappedBy property of @OneToMany to specify the owner side of the relation.

The opposide side of who declares mappedBy property is the owner side of the relation.

Many to many bidirectional

class CD
  @ManyToMany (mappedBy="appearsOnCDs")
  List<Artist> createdByArtists;
  
class Artist
  @ManyToMany
  @JoinTable(name="jnd_art_cd",
    joinColumns=@JoinColumn(name="artist_id")
    inverseJoinColumns=@JoinColumn(name="cd_id"))
  List<CD> appearsOnCDs;

@OrderBy

class Comment
  Date postedDate;
  String user;
  String text;
  
class News
  @OneToMany(EAGER) # eager or lazy, not important
  @OrderBy("postedDate DESC")
  List<Comment> comments;

The retrieved records will be auto automatically ordered by postedDate.

@OrderColumn

class News
  @OneToMany()
  @OrderColumn(name="post_index")
  List<Comment> comments;

With @OrderColumn, given List ordering is strictly applied and returned back.

This creates a post_index column on the auto created join table to enable strict ordering as SQL servers does not guarantee any orders while returning without order by keyword. If no parameters were given to @OrderColumn it will decide the column name automatically.

Note that @OrderBy and @OrderColumn cannot be used at the same time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment