使用复合键时尝试保存实体时出现异常。这是我尝试保存到的异常,模型和存储库。有人可以帮忙吗?
org.springframework.beans.TypeMismatchException:转换失败
'org.CheckType _ $$ _ jvst96c_4'类型的属性值转换为必需的类型
属性“ checkType”的“ int”;嵌套异常为
java.lang.IllegalArgumentException:无法转换类型的值
将'org.CheckType _ $$ _ jvst96c_4'设置为属性的必需类型'int'
'checkType':PropertyEditor
[org.springframework.beans.propertyeditors.CustomNumberEditor]
返回了类型'org.CheckType _ $$ _ jvst96c_4'的不合适的值
@Entity
public class CheckType {
@Id
private int id;
@NotNull
private String name;
@OneToMany(mappedBy = "checkType")
private List<ClientCheck> checks;
//getters and setters
}
@Entity
public class Offer {
@Id
@Column(name = "offerid")
private Integer offerId;
//...
@OneToMany(mappedBy = "offer")
private List<ClientCheck> clientCheckList;
//getters and setters
}
@Entity
@IdClass(ClientCheckId.class)
public class ClientCheck {
@Id
@ManyToOne
@JoinColumn(name = "offer_id", referencedColumnName = "offerid")
private Offer offer;
@Id
@ManyToOne
@JoinColumn(name = "check_type_id", referencedColumnName = "id")
private CheckType checkType;
@Id
private Date timestamp;
private String result;
//getters and setters
}
public class ClientCheckId implements Serializable {
private int offer;
private int checkType;
private Date timestamp;
//getters and setters
//equals and hashCode
}
public interface ClientCheckRepo extends JpaRepository<ClientCheck, ClientCheckId> {
}
最佳答案
如果另一个实体是组合键的一部分,则必须在ID类中声明该实体,而不是在其ID中声明:
public class ClientCheckId implements Serializable {
private int offer;
private CheckType checkType;
private Date timestamp;
//getters and setters
//equals and hashCode
}
如果您想了解Hibernate的工作方式,则该错误消息非常容易理解:
org.CheckType_$$_jvst96c_4
是类的增强版本,Hibernate试图通过反射将其分配给checkType
的ClientCheckId
字段,但由于类型不兼容而失败。