Question

The ratings column in the (MySQL) database has type ENUM('G','PG','PG-13','R','NC-17') (notice the dashes). This:

@Entity
@Table(name = "movies")
public class Movie implements Serializable {

    @Enumerated(EnumType.STRING)
    private Rating rating;

    public static enum Rating {
        G("G"), NC_17("NC-17"), R("R"), PG("PG"), PG_13(
                "PG-13");

        private String label;

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

        public String getLabel() {
            return label;
        }

        @Override
        public String toString() { // added but still
            return label;
        }
    }
}

causes a Data truncated for column 'rating' at row 1 exception for NC_17("NC-17") (and PG_13("PG-13"), works for the other values) - nevermind the exception should read Data rejected for enum ENUM('G','PG','PG-13','R','NC-17') for column 'rating' at row 1.

This happens because it tries to insert the string NC_17 - I thought that adding toString() as above would fix this but apparently calls rating.name() to produce the string to insert (instead of rating.toString()).

Are there any workarounds or do I have to change the type of ratings to ENUM('G','PG','PG_13','R','NC_17') in the DB ?

Edit: from the comments - what I ask is why JPA is not calling toString() for an @Enumerated(EnumType.STRING) entity field on update ? So I can't put in the db arbitrary chars ? It seemed like an oversight to me but apparently it is not - so off for mysql

Was it helpful?

Solution

JPA uses the name() of the enum, and not what is returned by toString() which could be overridden and return something different every time it's called. name() doesn't have this problem, because it's final and is thus guaranteed to always return the same thing.

So, your simplest option is to rename the values in your database so as they match with the enum names.

If that's really not an option and you're using Hibernate, then you could define your own type, that would be used to transform the enum to a String and vice-versa by Hibernate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top