spring boot jpa
标签(空格分隔): springboot jpa
本文主要讲解内容:
- @OneToOne
- @OneToMany
- @ManyToOne
- @ManyToMany
关于在JPA中使用@OneToOne @OneToMany @ManyToOne @ManyToMany
1. @OneToOne
单向映射,在字段上使用@OneToOne注解和@JoinColumn(name=”xxxx”),其中xxxx为当前表中关联其他表的字段,该字段为其他表的主键
@Entity
@Table(name = "check_sub_records")
public class CheckSubRecord {
@OneToOne
@JoinColumn(name = "super_item_id")
private CheckSuperItem checkSuperItem;
...其他代码略
}
如上代码表示:super_item_id为check_sub_records表中的字段,其在关联表中的为CheckSuperItem对应表中的id字段。
2. @OneToMany
单向映射:
//one 的一方,many的一方无需使用主键
@Entity
@Table(name = "orders")
public class Order {
@OneToMany
@JoinColumn(name = "order_id")
@OrderBy("id asc")
private Set<OrderRecord> orderRecords;
...其他代码略
}
说明:@JoinColumn(name = “order_id”)中的order_id为many一方的外键字段
双向映射:在双向映射中需配合@ManyToOne使用
//one的一方
@Entity
@Table(name = "users")
public class User implements Serializable {
@OneToMany(mappedBy = "user")
@JsonIgnoreProperties("user")
private Set<Car> cars;
...其他代码略
}
//many 的一方
@Entity
@Table(name = "cars")
public class Car {
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
@JsonIgnoreProperties("cars")
private User user;
...其他代码略
}
说明:one的一方使用@OneToMany(mappedBy=”user”),user为Car中的user属性;@JsonIgnoreProperties(“user”)该注解可防止json转换进入死循环;many的一方使用@ManyToOne,@JoinColumn(name = “user_id”, referencedColumnName = “id”),其中name为cars(many)表中的外键字段,referencedColumnName为users(one)表的主键;@JsonIgnoreProperties(“cars”)该注解可防止json转换进入死循环。
3. 待续…@ManyToOne
4. 待续…@ManyToMany