如何在 JPA 中使用枚举 [英] How to use enums with JPA

查看:34
本文介绍了如何在 JPA 中使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的电影租赁系统数据库.每部电影都有一个评级属性.在 SQL 中,他们使用约束来限制该属性的允许值.

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.

CONSTRAINT film_rating_check CHECK 
    ((((((((rating)::text = ''::text) OR 
          ((rating)::text = 'G'::text)) OR 
          ((rating)::text = 'PG'::text)) OR 
          ((rating)::text = 'PG-13'::text)) OR 
          ((rating)::text = 'R'::text)) OR 
          ((rating)::text = 'NC-17'::text)))

我认为使用 Java 枚举将约束映射到对象世界会很好.但是由于PG-13"和NC-17"中的特殊字符,不可能简单地采用允许的值.所以我实现了以下枚举:

I think it would be nice to use a Java enum to map the constraint into the object world. But it's not possible to simply take the allowed values because of the special char in "PG-13" and "NC-17". So I implemented the following enum:

public enum Rating {

    UNRATED ( "" ),
    G ( "G" ), 
    PG ( "PG" ),
    PG13 ( "PG-13" ),
    R ( "R" ),
    NC17 ( "NC-17" );

    private String rating;

    private Rating(String rating) {
        this.rating = rating;
    }

    @Override
    public String toString() {
        return rating;
    }
}

@Entity
public class Film {
    ..
    @Enumerated(EnumType.STRING)
    private Rating rating;
    ..

使用 toString() 方法,方向 enum -> String 工作正常,但 String -> enum 不起作用.我收到以下异常:

With the toString() method the direction enum -> String works fine, but String -> enum does not work. I get the following exception:

【TopLink 警告】:2008.12.0901:30:57.434--ServerSession(4729123)--异常 [TOPLINK-116] (OracleTopLink Essentials - 2.0.1(构建 b09d-fcs (12/06/2007))):oracle.toplink.essentials.exceptions.DescriptorException 异常说明:未提供值 [NC-17] 中的转换值字段 [电影分级].映射:oracle.toplink.essentials.mappings.DirectToFieldMapping[rating-->FILM.RATING]描述符:RelationalDescriptor(de.fhw.nsdb.entities.Film -->[数据库表(电影)])

[TopLink Warning]: 2008.12.09 01:30:57.434--ServerSession(4729123)--Exception [TOPLINK-116] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DescriptorException Exception Description: No conversion value provided for the value [NC-17] in field [FILM.RATING]. Mapping: oracle.toplink.essentials.mappings.DirectToFieldMapping[rating-->FILM.RATING] Descriptor: RelationalDescriptor(de.fhw.nsdb.entities.Film --> [DatabaseTable(FILM)])

干杯

蒂莫

推荐答案

听起来您需要添加对自定义类型的支持:

Sounds like you need to add support for a custom type:

扩展 OracleAS TopLink 以支持自定义类型转换

这篇关于如何在 JPA 中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆