1

In my project I use an enum in some entities. The enum is to be stored in the database as an integer. To achieve this I use EclipseLink's ObjectTypeConverter.

I'd like to use annotations since I use Spring to omit the persistence.xml. The annotation to configure the ObjectTypeConverter must be specified on an entity. I don't feel the need to specify the annotation on all classes that use this enum as this is redundant and not maintainable. Specifying it once on some entity would work but this doesn't make sense in an OOP design (or any design for that mater). A solution would be to annotate the enum with @ObjectTypeConverter, but this doesn't work since the enum isn't an entity.

Example that isn't working but would be ideal:

@Entity
public class ExampleEntity
{
    @Id
    private Long id;
    @Convert("exampleenum")
    private ExampleEnum ee;
}

@ObjectTypeConverter(name = "exampleenum", objectType = ExampleEnum.class, dataType = Integer.class,
    conversionValues =
        {
            @ConversionValue(objectValue = "A", dataValue = "100"),
            @ConversionValue(objectValue = "B", dataValue = "200"),
            @ConversionValue(objectValue = "C", dataValue = "300")
        })
public enum ExampleEnum
{
    A, B, C;
}

Example results in the following exception:

Exception Description: The converter with name [exampleenum] used with the element [field ee] in the class [class com.example.ExampleEntity] was not found within the persistence unit. Please ensure you have provided the correct converter name.

Since I'm using Spring, JPA and EclipseLink I accept any answer using these frameworks.

4

1 に答える 1

4

ドキュメントを読むと(最初はもっと慎重に行うべきでした)、次のことに気付きました。

ObjectTypeConverter は、名前で一意に識別される必要があり、クラス、フィールド、およびプロパティ レベルで定義でき、EntityMappedSuperclass、およびEmbeddableクラス内で指定できます。

@Entity(これにはテーブルが必要なため) または@MappedSuperclass(これは意味がないため) で列挙型に注釈を付けることはできませんでした@Embeddableが、ある意味では意味があります。列挙型をマークすると、@Embeddableうまくいきました:

@Embeddable
@ObjectTypeConverter(...)
public enum ExampleEnum
...
于 2012-12-10T15:07:35.730 に答える