我有一个这样的实体:
@Entity(name = "A")
public class A implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String A_Id;
private String field1;
private String field2;
@ElementCollection
@CollectionTable(name = "B", joinColumns = @JoinColumn(name = "A_Id"))
private Set<B> b;
// getters and setters
}
@Embeddable
public class B implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
@Column(name = "VALUE", length = 255, columnDefinition = "TEXT")
@Convert(converter = ObjectConverter.class)
private Object value;
// getters and setters
}
转换器类如下所示:
@Converter(autoApply = true)
public class ObjectConverter implements AttributeConverter<Object, String> {
private static String getType(Object obj) {
if (obj instanceof Boolean) {
return "b";
} else if (obj instanceof Integer || obj instanceof Long) {
return "i";
} else if (obj instanceof Double || obj instanceof Float) {
return "d";
} else if (obj instanceof String) {
return "s";
}
}
public String convertToDatabaseColumn(Object anyType) {
if (anyType == null) {
return null;
}
return String.format("%s:%s", getTypeCode(anyType), anyType.toString());
}
public Object convertToEntityAttribute(String encoded) {
if (encoded == null) {
return null;
}
final String val = encoded.substring(2);
switch (encoded.charAt(0)) {
case 'b':
return Boolean.parseBoolean(val);
case 'i':
return Long.parseLong(val);
case 'd':
return Double.parseDouble(val);
case 's':
return val;
default:
throw new IllegalArgumentException("Unexpected encoded string: " + encoded);
}
}
}
现在我从Hibernate中得到一个异常,像这样:
org.hibernate.MappingException:集合元素映射的列数错误:B类型:component [name,value]
但是,如果我不将java.lang.Object字段保留在嵌入式类中,而是将其保留在主实体中,则它可以正常工作。
例如,这很好用:
@Entity(name = "A")
public class A implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String A_Id;
private String field1;
private String field2;
@Column(name = "VALUE", length = 255, columnDefinition = "TEXT")
@Convert(converter = ObjectConverter.class)
private Object value;
// getters and setters
}
如何将Object字段保留在可嵌入类中,并使用Hibernate和JPA进行存储?