简体   繁体   中英

java hibernate override enum/string mapping values

I've got a following Hibernate model:

@Entity
@Table(name = "category")
public class Category {

    @Enumerated(EnumType.STRING)
    @Column(name = "type")
    private CategoryType type;

This is the enumeration referenced by hibernate:

public enum CategoryType {
    INCOME, OUTCOME;
}

THe corresponding database field is a varchar which takes 2 possible values: "CategoryIncome" and "CategoryOutcome".

This method actually calls hibernate:

public List<Category> findAllByType(CategoryType type) {
    session = sessionFactory.openSession();
    tx = session.beginTransaction();
    Query query = session.createQuery(
        "FROM Category WHERE type = :type");
    query.setParameter("type", type);
    List list = query.list();
    tx.commit();
    session.close();
    return list;
}

I managed to get my code work (I mean it compiles), but it works badly - it executes following SQL query:

WHERE type = "INCOME"

whereas I would like it to be:

WHERE type = "CategoryIncome"

How can I map enum values into string values for hibernate? I know that EnumType.STRING tells hibernate to cast the enum values to string (could be EnumType.ORDINAL to cast it to integers). But how can I override the default enum-string mapping?

You will have to use your customized usertype for Hibernate persistance, Hibernate uses name() function of enum to get string representation, not toString() .

See this Hibernate @Enumerated mapping

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