Spring,JPA,Postgresql - 不能使用自定义类型作为ID

时间:2016-10-05 23:32:49

标签: java postgresql jpa

我得到例外:

  

org.postgresql.util.PSQLException:错误:运算符不存在:uuid = bytea
  提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。

我有JPA实体

@Entity(name = "products")
class JpaProductEntity {

    @Id
    private ProductId id;

    private String payload;

    private Integer version;

    public JpaProductEntity() {
    }

    public void setId(ProductId id) {
        this.id = id;
    }

    public String getPayload() {
        return payload;
    }

    public void setPayload(String payload) {
        this.payload = payload;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }
}

Id class

 public class ProductId  implements Serializable {

    private static final long serialVersionUID = -6110163899364126142L;

    private String identifier;

    public ProductId(String identifier) {
        this.identifier = identifier;
    }

    public static ProductId from(String identifier) {
        Assert.notNull(identifier, "Identifier cannot be null");
        return new ProductId(identifier);
    }

    public static ProductId generate() {
        return new ProductId(Id.generateIdentifier());
    }
}

此外,转换器:

@Converter(autoApply = true)
public class ProductIdPostgresUuidConverter implements AttributeConverter<ProductId, UUID> {

    @Override
    public UUID convertToDatabaseColumn(ProductId attribute) {
        return UUID.fromString(attribute.toString());
    }

    @Override
    public ProductId convertToEntityAttribute(UUID dbData) {
        return ProductId.from(dbData.toString());
    }
}

看来,转换器完全不起作用(我在转换器方法中设置了断点,但没有任何反应,调试器不会进入那里)。

1 个答案:

答案 0 :(得分:0)

试试这个:

@Entity(name = "products")
class JpaProductEntity {

  @Type(type = "pg-uuid") // tells what type will be internally used by DB
  // Definitely need to instruct JPA to use your converter
  @Convert(converter = ProductIdPostgresUuidConverter.class)
  @Id
  private ProductId id;

}

提示:您可能有多个相同类型的转换器,可供您自行决定使用。您需要明确告诉JPA使用哪一个。