开发者

Hibernate Projections.sum() over an enum

I need some help with Hibernate Projections.

I have a class called Activity with a property "duration" which is an Enum. Duration is a Integer field on the Oracle Database. I have annotated the enum.


@TypeDefs({
    @TypeDef(
        name = "Duration", 
        typeClass = GenericEnumUserType.class, 
        parameters = {
            @Parameter(name = "enumClass", value = "myproject.Duration"),
            @Parameter(name = "identifierMethod", value = "getValue"),
            @Parameter(name =开发者_运维问答 "valueOfMethod", value = "getInstanceByValue") }) 
})
@Entity
@Table(name = "activity")
public class Activity {
...
private Duration duration;
...
}

The enum Duration has methods getValue() and getInstanceByValue(). The Value is an Integer.

I need to sum up the dutation of some Acitivities, that match my criterias. My DetachedCriteria looks something like this:


DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Activity.class);
...
detachedCriteria.setProjection(Projections.sum("duration"));

When I execute this detachedCriteria I get the following ClassCastException:

myproject.Duration cannot be cast to java.lang.Integer

How can I sum over an enumeration field? It works on the database with pure SQL, therefore it should work with hibernate too somhow I assume.

Thanks for any help.


I would map the map the column to an additional field that is of type int. This field needs to be mapped as readonly to avoid ambiguity:

@Entity
@Table(name = "activity")
public class Activity {
  ...
  private Duration duration;

  @Column(name = "duration", updatable = false, insertable = false) //mapped to the same columnn!
  private int durationNumeric
   ...
}

Then you rewrite your aggregate query along these lines:

detachedCriteria.setProjection(Projections.sum("durationNumeric"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜