How to use enums with JPA

前端 未结 11 1106
梦如初夏
梦如初夏 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:12

    i don't know internals of toplink, but my educated guess is the following: it uses the Rating.valueOf(String s) method to map in the other direction. it is not possible to override valueOf(), so you must stick to the naming convention of java, to allow a correct valueOf method.

    public enum Rating {
    
        UNRATED,
        G, 
        PG,
        PG_13 ,
        R ,
        NC_17 ;
    
        public String getRating() {
            return name().replace("_","-");;
        }
    }
    

    getRating produces the "human-readable" rating. note that the "-" chanracter is not allowed in the enum identifier.

    of course you will have to store the values in the DB as NC_17.

提交回复
热议问题