Hibernate自关联时无法更新@JoinColumn产生的字段

实体类

public class Department {


    private String id;

    private String name;

    private String description;

    private Department parent;

    private Set<Department> children = new HashSet<>();

    public Department() {
    }

    @Id
    @Column(name = "dept_id")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    public Department getParent() {
        return parent;
    }

    public void setParent(Department parent) {
        this.parent = parent;
    }

    @OneToMany(targetEntity = Department.class, mappedBy = "parent", fetch = FetchType.LAZY)
    @LazyCollection(LazyCollectionOption.FALSE)
    public Set<Department> getChildren() {
        return children;
    }

    public void setChildren(Set<Department> children) {
        this.children = children;
    }

}

测试方法

@Test
    public void test03() {
        Set<Department> depts = new HashSet<>();
        Department dept = new Department();
        Department dept2 = new Department();
        dept.setName("kkkkk");
        dept2.setName("mmmmmm");
        dept.setId(getUUID());
        dept2.setId(getUUID());
        depts.add(dept2);
        dept.setChildren(depts);
        departmentDao.save(dept2);
        departmentDao.save(dept);
    }

结果

能正常往数据库中添加值,但@JoinColumn(name = "parent_id")所生成的列无法更新数据,在navicat中parent_id有下拉框,又查看建表语句,有关联关系。但没法给parent_id这列添加数据,在navicat里也不行。

生成的数据表的建表语句:

CREATE TABLE `department` (
  `dept_id` varchar(255) NOT NULL,
  `description` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `parent_id` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`dept_id`),
  KEY `FKmgsnnmudxrwqidn4f64q8rp4o` (`parent_id`),
  CONSTRAINT `FKmgsnnmudxrwqidn4f64q8rp4o` FOREIGN KEY (`parent_id`) REFERENCES `department` (`dept_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在navicat中给parent_id手动添加数据时的报错信息:
clipboard.png


用两张表进行一对多关联时就没有这个问题。

阅读 1.9k
评论 2017-11-02 提问
    1 个回答
    NULL
    • 139

    试试加上级联?
    cascade = CascadeType.ALL

    评论 赞赏 2017-11-02
      撰写回答

      登录后参与交流、获取后续更新提醒