Hibernate:为什么在没有mappedBy的@OneToMany中连接中间表?



我有一个层级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;
}

@OneToMany中没有mappedBy = "department",我得到一个不存在的表,从log:

/* 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命名为我的表名的连接?

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

最新更新