Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an Enum using the addScalar() method with Hibernate

I have:

@Column(name = "UserType", nullable = false)
@Enumerated(EnumType.STRING)
private UserType userType;

How to return this field by SQL request using addScalar() method?

like image 794
Dark Hydra Avatar asked Jul 07 '14 19:07

Dark Hydra


1 Answers

This is how you add an Enum to a SQLQuery

  1. You define a properties object

    Properties params = new Properties();
    params.put("enumClass", "UserType");
    params.put("type", "12"); /*EnumType.STRING type = 12 */
    
  2. You resolve your enum type:

    Type userEnumType = sessionFactory.getTypeHelper().custom(UserType.class, params);
    
  3. You execute your query:

    List<SomeEntity> result = getSession().createSQLQuery("select e from SomeEntity ")
        .addScalar("userType", userEnumType)
        .setResultTransformer(Transformers.aliasToBean(SomeEntity.class))
        .list();
    
like image 81
Vlad Mihalcea Avatar answered Sep 22 '22 07:09

Vlad Mihalcea