Hibernate注解配置N:N关联

多对多

通过 @ManyToMany 注解定义多对多关系,同时通过 @JoinTable 注解描述关联表和关联条件。其中一端定义为 owner, 另一段定义为 inverse(对关联表进行更新操作,这段被忽略)。

@Entity

public class Employer implements Serializable {

  @ManyToMany(

    targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,

    cascade={CascadeType.PERSIST, CascadeType.MERGE}

  )

  @JoinTable(

    name="EMPLOYER_EMPLOYEE",

    joinColumns=@JoinColumn(name="EMPER_ID"),

    inverseJoinColumns=@JoinColumn(name="EMPEE_ID")

  )

  public Collection getEmployees() {

    return employees;

  }

  ...

}

@Entity

public class Employee implements Serializable {

  @ManyToMany(

    cascade = {CascadeType.PERSIST, CascadeType.MERGE},

    mappedBy = "employees",

    targetEntity = Employer.class

  )

  public Collection getEmployers() {

    return employers;

  }

}

默认值:

关联表名:主表表名 + 下划线 + 从表表名;关联表到主表的外键:主表表名 + 下划线 + 主表中主键列名;关联表到从表的外键名:主表中用于关联的属性名 + 下划线 + 从表的主键列名。

用 cascading 实现传播持久化(Transitive persistence)

cascade 属性接受值为 CascadeType 数组,其类型如下:

• CascadeType.PERSIST: cascades the persist (create) operation to associated entities persist() is called or if the entity is managed 如果一个实体是受管状态,或者当 persist() 函数被调用时,触发级联创建(create)操作。

• CascadeType.MERGE: cascades the merge operation to associated entities if merge() is called or if the entity is managed 如果一个实体是受管状态,或者当 merge() 函数被调用时,触发级联合并(merge)操作。

• CascadeType.REMOVE: cascades the remove operation to associated entities if delete() is called 当 delete() 函数被调用时,触发级联删除(remove)操作。

• CascadeType.REFRESH: cascades the refresh operation to associated entities if refresh() is called  当 refresh() 函数被调用时,出发级联更新(refresh)操作。

• CascadeType.ALL: all of the above  以上全部

原文地址:https://www.cnblogs.com/winkey4986/p/2575257.html