Last active
December 28, 2015 03:11
-
-
Save dungdm93/30696cc07654e0504dc9 to your computer and use it in GitHub Desktop.
[Java] [JPA] Map @OneToMany, @manytoone example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@OneToMany phone.onwer
@ManyToOne employee.phones
employee ↔ phone