Java hibernate overrides enum / string values

I have the 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 sleep mode:

 public enum CategoryType { INCOME, OUTCOME; } 

The corresponding database field is varchar, which takes two 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 to work (I mean that it compiles), but it does not work well - it executes the following SQL query:

 WHERE type = "INCOME" 

whereas I would like to:

 WHERE type = "CategoryIncome" 

How to compare enum values ​​in string values ​​for sleep mode? I know that EnumType.STRING tells hibernate to pass enum values ​​to a string (maybe EnumType.ORDINAL to pass it to integers). But how can I override the default enumeration string matching?

+4
source share
1 answer

You will need to use your custom type for Hibernate persistance, Hibernate uses the name() function enum to get a string representation, not toString() .

Watch this Hibernate @Enumerated mapping

+4
source

All Articles