JPA中如何定义实体类的关系?

JPA中可以通过以下方式定义实体类之间的关系:

  1. @OneToOne:一对一关系。一个实体的对象与另一个实体的对象有一对一的关系。
@Entity
public class User {  
    @Id 
    private int id;  

    @OneToOne
    private Info info;
}

@Entity
public class Info {  
    @Id 
    private int id;  

    @OneToOne(mappedBy = "info")
    private User user;
}
  1. @OneToMany:一对多关系。一个实体的对象与多个其他实体的对象有关系。
@Entity
public class User {  
    @Id 
    private int id;  

    @OneToMany
    private Set<Order> orders; 
}

@Entity
public class Order {  
    @Id
    private int id;

    @ManyToOne 
    private User user;
} 
  1. @ManyToOne:多对一关系。多个实体的对象与一个实体的对象有关系。
@Entity 
public class Order {  
    @Id
    private int id;

    @ManyToOne 
    private User user; 
}

@Entity
public class User {  
    @Id 
    private int id;  

    @OneToMany(mappedBy = "user")
    private Set<Order> orders; 
}
  1. @ManyToMany:多对多关系。多个实体的对象与多个实体的对象有关系。
@Entity
public class User {  
    @Id 
    private int id;  

    @ManyToMany 
    private Set<Role> roles; 
}

@Entity
public class Role {  
    @Id
    private int id;

    @ManyToMany(mappedBy = "roles") 
    private Set<User> users;   
}