Skip to content

Instantly share code, notes, and snippets.

@dungdm93
Last active December 28, 2015 03:11
Show Gist options
  • Save dungdm93/30696cc07654e0504dc9 to your computer and use it in GitHub Desktop.
Save dungdm93/30696cc07654e0504dc9 to your computer and use it in GitHub Desktop.
[Java] [JPA] Map @OneToMany, @manytoone example
import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
public String firstName;
public String lastName;
@OneToMany(mappedBy = "owner", cascade = CascadeType.ALL)
@MapKeyColumn(name = "phone_type")
public Map<String, Phone> phones = new HashMap<>();
@Override
public String toString() {
return String.format("Employee #%d : %s %s", id, firstName, lastName);
}
}
import javax.persistence.*;
@Entity
public class Phone {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
public String number;
public String provider;
@ManyToOne
public Employee owner;
@Override
public String toString() {
return String.format("Phone #%d : %s (%s)", id, number, provider);
}
}
@dungdm93
Copy link
Author

  • ver 01: uni-directional @OneToMany phone.onwer
  • ver 02: @ManyToOne employee.phones
  • ver 03: ver 01 + ver 02
  • ver 04: refine relationship : bi-directional employee ↔ phone
  • ver 05: customize the map-key column

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