注解@OneToMany@ManyToOne和@ManyToMany的使用总结

时间:2025-03-19 22:51:15

0 背景

       项目中用到@OneToMany、@ManyToOne和@ManyToMany,以评论和回复为例(一个评论会有多条回复),按照映射策略,分为外键关联、表关联和默认关联。总结它们的使用方法如下:

1 外键关联

@OneToMany

@Entity
public class Comment{

    private String id;

    @OneToMany( mappedBy="comment", cascade = {})   //mappedBy表示双向关系;cascade删除评论时级联删除回复
    @OrderBy( value="CREATED_DATE asc" )        //按创建日期升序查询
    private List<Reply> replyList = new ArrayList<>();
}

@ManyToOne

@Entity
public class Reply{

    private String id;

    @ManyToOne( fetch =  )       //关联取数据,eager表示立即加载; lazy表示懒加载,在对性能要求不高时使用
    @JoinColumn( name="COMMENT_ID", referencedColumnName= "ID")
    private Comment comment;
}

当fetch = 时,LAZY阻挡了除ID以外的所有访问,解决的办法有: 
1) 通过ID从数据库重新拿一次需要的数据;
2) 将改成 EAGER ,不适用快速查询

2 表关联

@OneToMany

@Entity
public class CustomerEO implements  {
  ...
  @OneToMany(cascade = {  })  
  @JoinTable(name="ref_customer_address",
           joinColumns={ @JoinColumn(name="customer_id",referencedColumnName="id")},
           inverseJoinColumns={@JoinColumn(name="address_id",referencedColumnName="id")})
  private Collection<AddressEO> addresses = new ArrayList<AddressEO>();
  ...
}

 

3 默认关联

这种情况下,只需在CustomerEO中标注@OneToMany即可

create table customer_address (
  customer_id int(20) not null,
  address_id int(20) not null unique
)
alter table customer_address add constraint fk_ref_customer foreign key (customer_id) references customer (id);
 
alter table customer_address add constraint fk_ref_address foreign key (address_id) references address (id);

注意:@ManyToMany和@OneToMany使用方法类似

综上,属性为一对多关系时,用映射策略--外键关联。属性为多对多关系时,用映射策略--表关联!