Hibernate:为什么在@OneToMany中没有mappedBy的情况下加入中间表?

时间:2014-08-12 15:42:39

标签: hibernate jpa

我有一个层次结构Employee ==> Department

@Table(name = "EMPL")
class Employee {
    @Id
    @Column(name = "ID", nullable = false, unique = true, updatable = false)
    private Integer id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.REFRESH)
    @JoinColumn(name = "DEPAR", referencedColumnName = "ID", nullable = false)
    private Department department;
}

@Table(name = "DEPAR")
class Department {
    @Id
    @Column(name = "ID", nullable = false, unique = true, updatable = false)
    private Integer id;

    @OneToMany(cascade = CascadeType.REFRESH)
    private Set<Employee> employees;
}

mappedBy = "department"中没有@OneToMany我从日志中加入不存在的表:

/* delete collection com.evil.entity.Department.employees */ delete 
    from
        DEPAR_EMPL
    where
        DEPAR_ID=?

或:

select ...
from
    DEPAR_EMPL employees_ 
inner join
    EMPL emplx1_ 
        on employees_.lvl2s_ID=emplx1_.ID 
inner join
    DEPAR deparx2_ 
        on emplx1_.LVL1=deparx2_.ID 
where
    employees_.DEPAR_ID=?

为什么Hibernate使用不存在的表 DEPAR_EMPL 生成查询,这些表命名为我的表名的串联?

1 个答案:

答案 0 :(得分:3)

因为如果你没有指定mappedBy,OneToMany关联就不再是ManyToOne关联的反面了。它因此成为一个完全不同的关联,并且由于您没有指定如何映射这个新关联,因此假定OneToMany单向的默认映射:一个名为您正在看到它的方式的连接表。