出于遗留原因,我在数据库中有组合键,因此我使用@IdClass来映射它们(在使用@Embeddedid之前,但它具有自己的错误)。但是,每当我尝试保存包含代理作为ID字段的组合键实体时,我都会遇到问题。 我做了一个非常简单的示例来隔离此问题(示例使用Spring Data,但我认为它无关紧要)。 ps。我知道没有必要调用.save,但不会引起异常。
@Entity
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String fileName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
@IdClass(ProductImage.ProductImageId.class)
public class ProductImage {
public static class ProductImageId implements Serializable {
private static final long serialVersionUID = 8542391285589067304L;
private Long product;
private Long image;
public ProductImageId() {
}
public Long getProduct() {
return product;
}
public void setProduct(Long product) {
this.product = product;
}
public Long getImage() {
return image;
}
public void setImage(Long image) {
this.image = image;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProductImageId that = (ProductImageId) o;
return Objects.equals(product, that.product) &&
Objects.equals(image, that.image);
}
@Override
public int hashCode() {
return Objects.hash(product, image);
}
}
@ManyToOne(fetch = FetchType.LAZY)
@Id
private Product product;
@ManyToOne(fetch = FetchType.LAZY)
@Id
private Image image;
private Integer number;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
List<ProductImage> productImages = productImageRepository.findAll();
productImages.get(0).setNumber(456);
productImageRepository.save(productImages.get(0));
原因:java.lang.IllegalArgumentException:无法将类型“ com.example.springbootnewplayground.Product $ HibernateProxy $ AJ38NiN6”的值转换为属性“ product”的必需类型“ java.lang.Long”:PropertyEditor [org。 springframework.beans.propertyeditors.CustomNumberEditor]返回了类型不正确的值'com.example.springbootnewplayground.Product $ HibernateProxy $ AJ38NiN6' 在org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:258)〜[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE] 在org.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585)〜[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE] ...省略了69个共同的框架