我尝试使用 Hibernate ORM 在我的数据库中保留实体。我的entity class
@Entity
@Table(name = "company")
public class Company implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String name;
@OneToMany(mappedBy = "company")
@LazyCollection(LazyCollectionOption.FALSE)
private Collection<Employee> employees;
存储库
@Repository
@Transactional(propagation = Propagation.REQUIRED)
public class HibernateCompanyRepository implements CompanyRepository {
@Autowired
HibernateTemplate template;
@Override
public Company getCompany(int id) {
return template.get(Company.class, id);
}
@Override
public Collection<Company> getCompanies() {
return template.loadAll(Company.class);
}
@Override
public void addCompany(Company employee) {
template.save(employee);
}
@Override
public void deleteCompany(int id) {
template.delete(template.get(Company.class, id));
}
@Override
public void updateCompany(Company company) {
template.update(company);
}
}
这是我的控制器
@Controller
@RequestMapping("/company")
public class CompanyController {
@Autowired
CompanyRepository companyRepository;
@RequestMapping(value = "/{id}",
method = RequestMethod.GET,
produces = "application/json")
@ResponseBody public Company getCompany(@PathVariable("id") Integer id) {
return companyRepository.getCompany(id);
}
@RequestMapping(method = RequestMethod.PUT,
consumes = "application/json",
headers = "content-type=application/json")
public String updateCompany(@RequestBody Company company) {
companyRepository.updateCompany(company);
return "redirect:/company/" + company.getId();
}
// another methods ommited
}
旧JSON
{
"name" : "IBM",
"employees" : [
{
"name" : "John",
"id" : 2
},
{
"name" : "Bill",
"id" : 4
}
],
"id" : 2
}
更新了JSON(Bill已删除)
{
"name" : "IBM",
"employees" : [
{
"name" : "John",
"id" : 2
}
],
"id" : 2
}
我在updateCompany()
方法中收到了一个Employee实体。 Entity
已成功更新。它改变了员工的集合(例如我删除了一名员工)。但是Hibernate不能坚持这个更新的实体。当我试图检索它时,我发现没有任何变化。有任何建议如何修复它?
UPD:
我首先尝试更新已删除的员工
@Override
public void updateCompany(Company company) {
Company oldCompany = getCompany(company.getId());
for (Employee employee : oldCompany.getEmployees()) {
if (!company.getEmployees().contains(employee)) {
employee.setCompany(null);
template.update(employee);
}
}
template.update(company);
}
获得例外
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DuplicateKeyException: a different object with the same identifier value was already associated with the session: [eu.flavio.restful.entity.Company#2]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [eu.flavio..restful.entity.Company#2]
答案 0 :(得分:0)
对Hibernate来说最重要的是双向关联的所有者方面。所有者方是没有mappedBy
属性的一方。这就是它寻找实体之间的关联是否存在的地方。
因此,所有者方Employee.company
。 Company.employees
是相反的一面。如果您希望Bill不再成为IBM的一部分,您必须确保将Bill的公司设置为null。