How to use enums with JPA

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

    What about this

    public String getRating{  
       return rating.toString();
    }
    
    pubic void setRating(String rating){  
       //parse rating string to rating enum
       //JPA will use this getter to set the values when getting data from DB   
    }  
    
    @Transient  
    public Rating getRatingValue(){  
       return rating;
    }
    
    @Transient  
    public Rating setRatingValue(Rating rating){  
       this.rating = rating;
    }
    

    with this you use the ratings as String both on your DB and entity, but use the enum for everything else.

提交回复
热议问题