Hibernate SQL Transformation Fails for Enum Field Type

Hibernate SQL transformation fails for Enum field type

Assuming that the java enum type that corresponds to column b is Foo.ProfileStateEnum, the following code snippet should work for you. (I tested with Hibernate 4.1.6)

import java.util.Properties;
import org.hibernate.type.Type;
import org.hibernate.type.IntegerType;
import org.hibernate.internal.TypeLocatorImpl.TypeLocatorImpl;
import org.hibernate.type.TypeResolver.TypeResolver;
import org.hibernate.type.EnumType;

Properties params = new Properties();
params.put("enumClass", "Foo.ProfileStateEnum");
params.put("type", "12"); /*type 12 instructs to use the String representation of enum value*/
/*If you are using Hibernate 5.x then try:
params.put("useNamed", true);*/
Type myEnumType = new TypeLocatorImpl(new TypeResolver()).custom(EnumType.class, params);

List<Profile> profileList= getSession().createSQLQuery("select a as ID, b from profiles")
.addScalar("ID", IntegerType.INSTANCE)
.addScalar("b", myEnumType )
.setResultTransformer(Transformers.aliasToBean(Profile.class))
.list();

Hibernate Custom SQL Enum transformation fails

I found a way to do it:

Properties params = new Properties();
params.put("enumClass", MyEnumClass.class.getName());
params.put("useNamed", true);

EnumType enumType = new EnumType();
enumType.setParameterValues(params);
CustomType customType = new CustomType(enumType);

final Query query = getCurrentSession().createSQLQuery(MY_CUSTOM_SQL)
.addScalar("col1", customType)
.addScalar("col2", StandardBasicTypes.INTEGER)
.setLong("someSqlVar", someVal)
.setResultTransformer(Transformers.aliasToBean(MyCustomBean.class));

return query.list();

Create form for domain object with multiselect Enum field fails with 'Property xxx is type-mismatched'

I was able to get past my error by making the following changes. I added a hasMany statement in DomainObject

static hasMany = [categories: Category]

and I made these changes in the create.gsp file:

<f:field property="categories">
<g:select
multiple="true"
name="${property}"
from="${Category?.values()}"
optionKey="key"
value="${domainObject?.categories}"
/>
</f:field>

Hibernate - Use native query and alias to Bean with enum properties?

Firstly, you shouldn't use

private EnumType prop3;

but

private ActualEnum prop3;

Where ActualEnum is your own enum type (for example, Fruits to distinguish apples and oranges).

Second, you hibernate mapping is irrelevant when you use native sql.

Now, there are couple of options I can propose. You can try to use addEntity() instead of bunch of scalars. It's possible that Hibernate will recognize enum property and map correctly.

Other option is to have non public setter that would take string from database, convert it to enum and set actual property.

Finally, you can customize transformer. But it's probably most complex option.



Related Topics



Leave a reply



Submit