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手动添加数据时的报错信息:
用两张表进行一对多关联时就没有这个问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试加上级联?
cascade = CascadeType.ALL