zoukankan      html  css  js  c++  java
  • 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  以上全部

  • 相关阅读:
    JObject提取Json字符串中某字段的值
    将DataTable导出为Excel文件的方法
    剑指offer-面试题39-数组中出现次数超过一半的数字-快速排序
    剑指offer-拓展训练-N皇后的问题-全排列
    剑指offer-拓展训练-字符的所有组合-全组合
    剑指offer-面试题38-字符串的排列-全排列
    剑指offer-面试题36-二叉搜索树与双向链表-中序遍历
    java多线程技能-使用多线程-继承Thread类
    剑指offer-面试题35-复杂链表的复制-链表
    剑指offer-面试题34-二叉树中和为某一值的路径-二叉树遍历
  • 原文地址:https://www.cnblogs.com/winkey4986/p/2575257.html
Copyright © 2011-2022 走看看