关于在JPA中使用@OneToOne @OneToMany @ManyToOne @ManyToMany

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

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值