如何重写javax.persistence.attributeconverter

eivnm1vs  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(394)

我有一个问题,想要覆盖实体的子类中的attributeconverter,但是子类中定义的转换器没有被调用。根据attributeconverter文档,这应该是一种方式,但它不适合我。我做错什么了?

@Entity
@org.hibernate.annotations.DynamicUpdate(value = true)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "DISCRIMINATOR", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("ORDER")
public class Order implements Serializable
{
...
    @Column(name = "PRODUCT_SERIALIZED", updatable = false)
    @Convert(converter = ProductConverter.class)
    protected Product product;
...
}
@Entity
@DiscriminatorValue("CUSTOMER_ORDER")
@Convert(attributeName = "product", converter = CustomerProductConverter.class)
public class CustomerOrder extends Order
{
...
balp4ylt

balp4ylt1#

似乎@convert不适合覆盖超类字段的现有转换器。我用另一种方法解决了。我通过cdi将conversionservice注入到超类的attributeconverter中,然后我可以专门化它。

@Converter
public class ProductConverter implements AttributeConverter<Product, String>
{
    ProductConverterService converterBean = null;

    @Override
    public String convertToDatabaseColumn(Product attribute)
    {
        return getConverterService().convertToDatabaseColumn(attribute);
    }

    @Override
    public Product convertToEntityAttribute(String dbData)
    {
        return getConverterService().convertToEntityAttribute(dbData);
    }

    public ProductConverterService getConverterService()
    {
        if (converterBean == null)
        {
            //since ProductConverter is obiously not managed via CDI
            converterBean = CDI.current().select(ProductConverterService.class).get();
        }
        return converterBean;
    }
}

相关问题