How to use enums with JPA

前端 未结 11 1079
梦如初夏
梦如初夏 2020-12-03 02:47

I have an existing database of a film rental system. Each film has a has a rating attribute. In SQL they used a constraint to limit the allowed values of this attribute.

11条回答
  •  旧巷少年郎
    2020-12-03 03:10

    You have a problem here and that is the limited capabilities of JPA when it comes to handling enums. With enums you have two choices:

    1. Store them as a number equalling Enum.ordinal(), which is a terrible idea (imho); or
    2. Store them as a string equalling Enum.name(). Note: not toString() as you might expect, especially since the default behaviourfor Enum.toString() is to return name().

    Personally I think the best option is (2).

    Now you have a problem in that you're defining values that don't represent vailid instance names in Java (namely using a hyphen). So your choices are:

    • Change your data;
    • Persist String fields and implicitly convert them to or from enums in your objects; or
    • Use nonstandard extensions like TypeConverters.

    I would do them in that order (first to last) as an order of preference.

    Someone suggested Oracle TopLink's converter but you're probably using Toplink Essentials, being the reference JPA 1.0 implementation, which is a subset of the commercial Oracle Toplink product.

    As another suggestion, I'd strongly recommend switching to EclipseLink. It is a far more complete implementation than Toplink Essentials and Eclipselink will be the reference implementation of JPA 2.0 when released (expected by JavaOne mid next year).

提交回复
热议问题