【问题标题】:Map configuration in HibernateHibernate 中的映射配置
【发布时间】:2015-12-03 05:08:32
【问题描述】:

我们在 Hibernate 中有一个要求,即假设我们有一个类名 Employee ,其中包含部门列表。但是这里的 Department 不包含任何 fields ,它只包含一个包含部门字段的地图。所以请告诉我Employee和Department类的Hibernate配置。

谢谢, 纳西普

【问题讨论】:

  • 在员工类中,我映射为@ElementCollection private List deptList;
  • 请编辑您的问题并提供一些示例代码

标签: hibernate hibernate-mapping


【解决方案1】:

也许您在谈论单向的一对多关系? 在这种情况下,您应该使用

@Entity
public class Employee {
    @OneToMany
    private Set<Department> departments;

    public Set<Department> getDepartments() {
        return departments;
    }

    public void setDepartments(Set<Department> departments)
    {
        this.departments = departments;
    }
    //....

}

@Entity
public class Department {
    // No link to Employee
    @Id
    private long id;
    private String name;
    //....

}

在这种情况下,您有一个从 Employee 到 Department 的引用,但没有从 Department 到 Employee 的引用.

UPD1:

如果你想映射基本类型,你可以使用 narsi 提到的 @ElementCollection:

@ElementCollection
Map<String, String> departments; 

【讨论】:

  • 是的 Amuza,只有这样,但在 Department 中,我们没有 id 和 name 属性,我们只有 Map。那么在这种情况下我们如何配置部门呢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 1970-01-01
相关资源
最近更新 更多