如何使用枚举与JPA [英] How to use enums with JPA
问题描述
CONSTRAINT film_rating_check CHECK
(((( (((评级)::文本=''::文本)OR
((评级)::文本='G'::文本))OR
((评级):: 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中的特殊字符,因此不可能简单地取得允许的值。所以我实现了以下枚举:
public enum Rating {
UNRATED(),
G(G),
PG(PG),
PG13(PG-13),
R(R),
NC17 (NC-17);
private String rating;
私人评级(String rating){
this.rating = rating;
}
@Override
public String toString(){
return rating;
}
}
@Entity
public class Film {
..
@Enumerated(EnumType.STRING)
private评级等级;
..
使用toString()方法,方向枚举 - > String工作正常,但是String - >枚举不起作用。我得到以下异常:
[TopLink警告]:2008.12.09
01:30:57.434 - ServerSession(4729123 ) - 异常[TOPLINK-116](Oracle
TopLink Essentials - 2.0.1(Build b09d-fcs(12/06/2007))):
oracle.toplink.essentials.exceptions.DescriptorException异常
说明:
字段[FILM.RATING]中的值[NC-17]未提供转换值。映射:
oracle.toplink.essentials.mappings.DirectToFieldMapping [rating - > FILM.RATING]
描述符:RelationalDescriptor(de.fhw.nsdb.entities.Film - >
[DatabaseTable (FILM)])
欢呼
timo
听起来您需要添加对自定义类型的支持:
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)))
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;
..
With the toString() method the direction enum -> String works fine, but String -> enum does not work. I get the following exception:
[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)])
cheers
timo
Sounds like you need to add support for a custom type:
Extending OracleAS TopLink to Support Custom Type Conversions
这篇关于如何使用枚举与JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!