【问题标题】:TypeConverter on Id Column in combination with jpqlId 列上的 TypeConverter 结合 jpql
【发布时间】:2014-11-21 12:13:56
【问题描述】:

我有一个由条形码描述为唯一 ID 的数据库实体。 为了更好地使用条形码,我添加了一个名为 Barcode 的类,其中包含 2 个值: - 条形码的价值 - 条形码的校验和 因为我想将它紧凑地保存在数据库中,所以我添加了一个属性转换器,它将条形码转换为格式为(值 + 校验和)的字符串

@Entity
@Table
public class Game implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Getter
    @Setter
    @Convert(converter = BarcodeConverter.class)
    private Barcode barcode;

    @Column
    @Getter
    @Setter
    private String title;

    @Column
    @Getter
    @Setter
    private String comment;
}

@Converter(autoApply=true)
public class BarcodeConverter implements AttributeConverter<Barcode, String> {

    public String convertToDatabaseColumn(Barcode attribute) {
        return attribute.getValue() + attribute.getChecksum();
    }

    public Barcode convertToEntityAttribute(String dbData) {
        return new Barcode(dbData);
    }
}

现在我不确定如何在我的应用程序中使用条形码/id 列:

1) 是否可以通过以下方式获取游戏对象:

entityManager.find(Game.class, new Barcode("012345", "7"));

2) 如何在 jpql 查询中使用条形码字段?我可以访问条形码对象的字段,还是隐式处理字符串? 例如,如果我想通过它们的校验和选择一些游戏,我是否可以这样写:

from Game g where g.barcode.checkum = 7 

from Game g where g.barcode like "%7"

3) 使用转换器实现的关系如何映射? 它们是通过转换器的字符串表示映射还是使用条形码对象的多个字段映射?

问候 圆珠笔

【问题讨论】:

    标签: java jpa jpql typeconverter


    【解决方案1】:

    您需要在应用程序中使用 Barcode 对象。您的 JPA 实现(例如 Hibernate)将为每个数据库访问使用转换器来进行转换。

    您可以在我的 github 存储库中找到一个示例:https://github.com/thjanssen/ColorConverter/blob/master/Converter/src/test/java/blog/thoughts/on/java/jpa21/TestColorConverter.java#L52

    【讨论】:

    • 您能否添加一个示例,您将如何访问 jpql 查询中的条形码?
    • 你需要在 JPQL 查询中访问字符串还是对象?
    • 谢谢你的榜样!我现在想知道的是如何在 where 子句中只使用蓝色组件的情况下进行查询。您是否通过查询中的对象访问来执行此操作,例如:SELECT r FROM Rectangle r WHERE color.blue = :blueValue 还是您需要使用数据库中的字符串来完成此操作,例如:SELECT r FROM Rectangle r WHERE color like '%|%|:蓝色|%'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2014-05-04
    • 2013-11-16
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多