简体   繁体   中英

How to map mysql enum type with hypen to JPA entity?

There's a table in mysql sakila.film which has field rating of type enum('G','PG','PG-13','R','NC-17') .

I'm trying to map this in JPA entity using type enum and @Enumerated(EnumType.STRING) but not able to, as java enum doesn't allow hyphen. Can't alter or update table also as it has lots of data and gives error -"Data truncated for column 'rating'"

How to proceed?

This sort of thing is what JPA Attribute Converters are designed to help achieve.

First you'll want to map your Java enum elements to the strings found in the database, and provide a lookup method for converting a string to an element:

public enum Rating {
    G("G"), // the string arguments should exactly match what's in the database.
    PG("PG"),
    PG13("PG-13"),
    R("R"),
    NC17("NC-17");

    private static final Map<String, Rating> LOOKUP = Arrays.stream(values())
            .collect(Collectors.toMap(Rating::getRating, Function.identity()));

    private final String rating;

    Rating(final String rating) {
        this.rating = rating;
    }

    public String getRating() {
        return rating;
    }

    public Rating fromString(final String rating) {
        // You may want to include handling for the case where the given string
        // doesn't map to anything - implementation is up to you.
        return LOOKUP.get(rating);
    }
}

Next you're going to want a class that implements javax.persistence.AttributeConverter :

public static class RatingConverter implements AttributeConverter<Rating, String> {
    @Override
    public String convertToDatabaseColumn(final Rating attribute) {
        return attribute.getRating();
    }

    @Override
    public Rating convertToEntityAttribute(final String dbData) {
        return Rating.fromString(dbData);
    }
}

From here you need to decide whether this converter should always be applied (it sounds like it probably should be), or not.

If you want it to always be used with no further configuration from you, then annotate your converter class with @javax.persistence.Converter(autoApply = true) .

If you want to choose when you use the converter, then you will need to add the annotation @javax.persistence.Convert(converter = RatingConverter.class) to the Rating attribute of each JPA entity that needs it.

Personally I usually nest the converters as a static class inside the class that they convert, but you don't have to if you'd rather keep them separate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM