我正在学习Hibernate(Spring)并面临从父项中删除子实体的奇怪问题。
这就是我所拥有的:
父实体:
**var app = angular.module('HelloApp', []);
app.controller('MyCtrl', function($scope) {
console.log('ctrl working');
$scope.test = function () {
nos=["5", "10", "15"];**
var kill=$scope.bob;
alert ("changed!"+ kill);
}
});
子实体:
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "company_id", referencedColumnName = "id")
List<CompanyObject> companyObjects;
}
这是我的表定义:
@Entity
public class CompanyObject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Enumerated(EnumType.STRING)
ObjectType type;
@ManyToOne
@JoinColumn(name = "company_id")
Company company;
}
而且,我还有以下CREATE TABLE `company` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8
CREATE TABLE `company_object` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`company_id` bigint(20) NOT NULL,
`type` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK__company` (`company_id`),
CONSTRAINT `FK__company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
方法:
update
一旦我启动// some code here
public void update(CompanyDto dto) {
Company company = repository.getCompanyById(companyId);
repository.save(dto.merge(company));
}
// some code here
public class CompanyDto {
private List<CompanyObjectDto> companyObjects = new ArrayList<>();
public Company merge(Company company) {
company.getCompanyObjects().clear();
for (CompanyObjectDto dto : companyObjects) {
company.getCompanyObjects().add(dto.to(company));
}
return company;
}
}
public class CompanyObjectDto {
ObjectType type;
public CompanyObject to(Company company) {
CompanyObject object = new CompanyObject();
object.setType(this.getType());
object.setCompany(company);
return object;
}
}
方法,我就会收到以下错误:update
。我对此进行了一些调查,发现如果我注释掉java.sql.SQLWarning: Column 'company_id' cannot be null
字符串就可以了,所以看起来将删除操作级联到公司对象时会出现问题。
答案 0 :(得分:1)
您收到错误是因为您要从List
删除对象,然后使用相同的List
作为对Company
对象的引用。见下面的代码:
private List<CompanyObjectDto> companyObjects = new ArrayList<>(); //Stmt 1
以上代码用于定义将在以下代码中引用的列表:
company.getCompanyObjects().clear(); //It will clear out all objects
for (CompanyObjectDto dto : companyObjects) { //Iterating over empty list defined in stmt 1.
company.getCompanyObjects().add(dto.to(company));
}
因此,您的外键将始终为null,这是不允许的,并抛出异常。
当您注释掉List#clear
行时,您的代码会起作用,因为在该方案中,列表已经有一些未修改的引用对象。
答案 1 :(得分:1)
您已经双向映射了您的实体Company和CompanyObject,即两个实体都与另一个实体有关系。
在这种情况下,只应该有一个@Joincolumn,并且必须选择一个实体作为拥有实体,另一个实体用'mappedby'标记关系(参见http://docs.oracle.com/javaee/6/api/javax/persistence/ManyToOne.html)。