开发者

How to get sum(boolean) as integer in hibernate's criteria query?

开发者 https://www.devze.com 2023-01-27 05:28 出处:网络
In a simple \'vote up / vote down\' scenario , I want to sum the total \'up\' count . criteria.add(Restrictions.eq(\"vote\" , Boolean.TRUE));

In a simple 'vote up / vote down' scenario , I want to sum the total 'up' count .

criteria.add(Restrictions.eq("vote" , Boolean.TRUE));
criteria.setProjection(Projections.rowCount());

The generated SQL is sum(this_.vote) as y1_ and generates correct sum value , but hibernate parsed it as 'boolean' value , all become 'true' ...

How to solve it ? ( if I don't need to change the 'vote' from boolean to integer )

environment : hibernate-3.6.0 , jpa2

Thanks a lot !开发者_StackOverflow中文版


What DB are you using? I think you might need to change the dialect with which hibernate is working.

Let hibernate use Tinyint for boolean variables.

Not on my working copmuter atm - sorry. If this might be the right direction get back at me and I will get an example later.

This might help you get started in the meantime: https://forum.hibernate.org/viewtopic.php?f=1&t=1008105

cheers

EDIT:

Ok. Since you're using Mysql, you might want to extend an existing MySQL Dialect - e.g. standard MySQL5Dialect:

 public class MySQL5DialectBooleanAsTinyint extends MySQL5Dialect {

  public MySQL5DialectBooleanAsTinyint() {
    super();
    registerColumnType(Types.BIT, "tinyint(1)");
  }

}

And that's it. To use your Custom Dialect, change your hibernate.cfg accordingly:

 <property name="hibernate.dialect">your.package.structure.dao.MySQL5DialectBooleanAsTinyint</property> 
0

精彩评论

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

关注公众号