Say I have an entity that contains an element collection of an embeddable type. The embeddable has an attribute that is an enumeration. I want to represent/encode values of the enumeration in the database as a single character, which is why I wrote a converter to do this. Modulo renaming of classes and attributes, the code looks like this:
{code:java} @Entity class Entity { // ... @ElementCollection @CollectionTable(name="entity_l", joinColumns=@JoinColumn(name="entity_id")) private List<Embeddable> list; // ... }
@Embeddable class Embeddable { @Column(nullable=false, updatable=false) @Convert(converter=MyEnumConverter.class) private MyEnum field; }
class MyEnumConverter implements AttributeConverter<MyEnum, Character> { /*...*/ } {code}
Using Postgres, when Hibernate creates that the database schema, it will map the embeddable's field to type `integer` rather than `character(1)`.
I have also tried the following, without any difference (still `integer` used in the database):
{code:java} @Entity class Entity { // ... @ElementCollection @CollectionTable(name="entity_l", joinColumns=@JoinColumn(name="entity_id")) @Convert(attributeName = "field", converter=MyEnumConverter.class) // Using @Convert(attributeName = "list.field", converter=MyEnumConverter.class) neither works. private List<Embeddable> list; // ... }
@Embeddable class Embeddable { @Column(nullable=false, updatable=false) private MyEnum field; }
class MyEnumConverter implements AttributeConverter<MyEnum, Character> { /*...*/ } {code}
My first question is whether the JPA spec covers this use case. I could not find any explicit statement that this would not be allowed. In fact, the [JPA Wikibook|https://en.wikibooks.org/wiki/Java_Persistence/Basic_Attributes#Converters_.28JPA_2.1.29] makes the following statement: {quote}Another option, if converting a custom type, is to have the Converter applied to *any mapped attribute* that has that type.{quote} My interpretation of this statement is that the example described above is a very valid use case. Then, however, the behavior I see seems to be a bug. What do you think?
As a last comment, I have other enumeration attributes in *entities* (rather than embeddables) where conversion to a single character works well and where the type in the database is indeed `character(1)`. |
|