JPA给@EmbeddedId加转换器提示需定义(sub)attributeName怎么解决?
错误原因
你的写法存在映射逻辑冲突:@EmbeddedId的语义是将VendorProductMappingPk内的所有属性,分别映射为数据库表的独立字段(也就是你代码里定义的vendor_id、product_id两个列)。而你直接在该字段上加@Convert,JPA会默认你是要转换嵌入类中的某一个子属性,因此要求你指定attributeName参数,所以抛出了对应的错误。
解决方案根据你的实际需求二选一
方案1:数据库仅存单个字符串类型的主键列
如果你希望将整个VendorProductMappingPk对象转换成一个字符串,存在单个主键列中,不需要单独的vendor_id、product_id字段,调整如下:
- 删除
VendorProductMappingPk类上的@Embeddable注解 - 实体类主键字段替换为
@Id+@Convert,不需要@EmbeddedId
@Entity @Table(name = "vendor_product") public class VendorProductMapping { @Id @Convert(converter = VendorProductMappingIdConverter.class) private VendorProductMappingPk id; // 其余业务字段根据需求调整,如果不需要关联Vendor、Product表可以直接删除对应属性 }
方案2:数据库保留vendor_id、product_id两个独立列
如果你只是需要对嵌入类中的单个字段做转换,或者只是在Java代码层面需要VendorProductMappingPk和字符串的转换能力,不需要映射到数据库:
- 如果是要转换嵌入类内的单个字段,使用
@Converts注解指定对应子属性即可:
@EmbeddedId @Converts(value = { @Convert(attributeName = "vendorId", converter = 对应vendorId的转换器类.class), @Convert(attributeName = "productId", converter = 对应productId的转换器类.class) }) private VendorProductMappingPk id;
- 如果只是Java代码层面需要转换能力,不需要和数据库映射挂钩,直接移除字段上的
@Convert注解,单独写工具类实现转换逻辑即可,不需要修改JPA映射配置。
内容的提问来源于stack exchange,提问作者Shravana More
相关产品推荐
相关产品推荐

