TypeConverter on Id Column in combination with jpql

684 Views Asked by At

I have an database entity that is described by an barcode as its unique id. To better use the barcode I've added a class called Barcode that contains 2 values: - The value of the barcode - The checksum of the barcode Because I want to save it compactly in the database I've added an attribute converter that converts me the Barcode into an String in the format (value + checksum)

@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);
    }
}

Now I'm not sure how I can use the barcode/id column in my application:

1) Is it possible to get a Game object by using:

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

2) How can I use the barcode field in a jpql query? Can I access the fields of the barcode object, or do I implicitly work on the string? Example if I want to select some games by their checksum do I do this by writing:

from Game g where g.barcode.checkum = 7 

or

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

3) How are relations mapped that are realized with the use of an converter? Are they mapped by the string representation from the converter or by using the multiple fields of the barcode object?

Greetings biro

1

There are 1 best solutions below

3
On

You need to use Barcode objects in your application. Your JPA implementation (e.g. Hibernate) will use the converter for every database access to do the conversion.

You can find an example in my github repo: https://github.com/thjanssen/ColorConverter/blob/master/Converter/src/test/java/blog/thoughts/on/java/jpa21/TestColorConverter.java#L52