How to use enums with JPA

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

    public enum Rating {
    
        UNRATED ( "" ),
        G ( "G" ), 
        PG ( "PG" ),
        PG13 ( "PG-13" ),
        R ( "R" ),
        NC17 ( "NC-17" );
    
        private String rating;
    
        private static Map ratings = new HashMap();
        static {
            for (Rating r : EnumSet.allOf(Rating.class)) {
                ratings.put(r.toString(), r);
            }
        }
    
        private static Rating getRating(String rating) {
            return ratings.get(rating);
        }
    
        private Rating(String rating) {
            this.rating = rating;
        }
    
        @Override
        public String toString() {
            return rating;
        }
    }
    

    I don't know how to do the mappings in the annotated TopLink side of things however.

提交回复
热议问题