HibernateException- Domain实例的标识符从X更改为Y.

时间:2016-05-28 06:12:37

标签: java hibernate jpa-2.0 spring-data-jpa

我在更新spring数据jpa中的父记录时遇到异常。

这是我的代码:

ParentEntity

@Entity
@Table(name = "CAMP")
@Getter
@Setter
public class Parent extends AbstractEntity  {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "tkeygenerator")
@GenericGenerator(name = "tkeygenerator", strategy = "com.custom.TKeyGenerator",
parameters = {@org.hibernate.annotations.Parameter(name = "sequence", value = "TKEY_SEQ")})
@Column(name = "TKEY", nullable = false)    
private String id;
@ManyToOne
@JoinColumn(name = "SUB_CAT_TYPE_CODE", referencedColumnName =   "SUB_CAT_TYPE_CODE")
private Child child;
@Column(name = "DATE")
@Basic
private LocalDate date;
}  

儿童实体

@Entity
@Table(name = "SUB_CAT_TYPE")
@AttributeOverrides({
@AttributeOverride(name = "code", 
                   column = @Column(name = "SUB_CAT_TYPE_CODE", length = 30)),
@AttributeOverride(name = "description", 
                   column = @Column(name = "SUB_CAT_TYPE_DESC", length = 255))})
@EqualsAndHashCode(callSuper = true)
public class Child extends AbstractTypeDesc {}

TestCode

public Parent update(@PathVariable("id") String id, @Valid @RequestBody  UpdateDto dto) {

      Parent parentObj = parentRepository.findById(id);
      mapper.map(dto, parentObj); // Dozer to map incoming dto to domain                  

      childRepository.findByCode(dto.child().getCode())
                     .map(child -> { 
                           parentObj.setChild(child);
                           return child;
                      });

      return parentRepository.save(parentObj); //Exception occurs here
}    

我在尝试将父实体中的子实体的代码变量更新为fk时遇到异常。它说can't alter code from X to Y

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我在上面的代码块中找出了更新操作出了什么问题。虽然不太清楚为什么它的发生。将dto映射到域的dozer映射导致问题,它正在改变子实体的值然后当我尝试时再次通过setter方法设置子实体它导致“Id alter exception”,虽然我也是同样的事情,我不知道为什么它采取不同的方式。下面是工作的工作代码。

测试代码应该像

public Parent update(@PathVariable("id") String id, @Valid @RequestBody       UpdateDto dto) {

Parent parentObj = parentRepository.findById(id);

childRepository.findByCode(dto.child().getCode())
                 .map(child -> { 
                       parentObj.setChild(child);
                       return child;
                  });
mapper.map(dto, parentObj); // Dozer dto to domain mapping was causing problem                   

return parentRepository.save(parentObj); 
}