本站首页    管理页面    写新日志    退出


«August 2025»
12
3456789
10111213141516
17181920212223
24252627282930
31


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7589143
建立时间:2006年5月29日




[Hibernate]解决Hibernate 3不支持 "&" 运算的SQL语句
软件技术

lhwork 发表于 2006/7/10 11:09:04

按位与运算(&)在许多数据库中都是支持的,遗憾的是,Hibernate 3在HQL中不支持&运算,如果你写了如下的HQL: where a.id & :mask = :target 则Hibernate报错:exception: unexpected char: '&'. 如何解决此问题?方法是利用Hibernate支持的自定义SQLFunction,定义一个bitand(a,b)的SQLFunction,然后,自己写一个解释器,生成a & b的SQL语句。 要实现一个自定义的SQLFunction,必须实现SQLFunction接口: /** * for more information, please visit http://www.crackj2ee.com * Copyright_2006, Liao Xuefeng * Created on 2006-4-19 */package com.crackj2ee.dev.hibernate; import java.util.List; import org.hibernate.Hibernate;import org.hibernate.QueryException;import org.hibernate.dialect.function.SQLFunction;import org.hibernate.engine.Mapping;import org.hibernate.engine.SessionFactoryImplementor;import org.hibernate.type.Type; /** * If don't have this 'bitand' function, hibernate will report  * exception: unexpected char: '&'. *  * @author Xuefeng */public class BitAndFunction implements SQLFunction {     public Type getReturnType(Type type, Mapping mapping) {        return Hibernate.LONG;    }     public boolean hasArguments() {        return true;    }     public boolean hasParenthesesIfNoArguments() {        return true;    }     public String render(List args, SessionFactoryImplementor factory) throws QueryException {        if (args.size() != 2) {            throw new IllegalArgumentException("BitAndFunction requires 2 arguments!");         }        return args.get(0).toString() + " & " + args.get(1).toString();    } } 然后,根据你使用的数据库方言,派生一个自定义的CustomSQLDialect: /** * for more information, please visit http://www.crackj2ee.com * Copyright_2006, Liao Xuefeng * Created on 2006-4-19 */package com.crackj2ee.dev.hibernate; import org.apache.commons.logging.LogFactory;import org.hibernate.dialect.SQLServerDialect; public class CustomSQLDialect extends SQLServerDialect {     public CustomSQLDialect() {        super();        registerFunction("bitand", new BitAndFunction());    } } 我们设定函数名为bitand,参数和返回值均为Hibernate.LONG,现在,用CustomSQLDialect替换配置文件中的设置,然后修改HQL: where bitand(a.id, :mask) = :target 编译,运行,观察Hibernate的SQL输出,执行成功!


阅读全文(7995) | 回复(1) | 编辑 | 精华
 


回复:解决Hibernate 3不支持 "&" 运算的SQL语句
软件技术

好学(游客)发表评论于2007/7/3 10:49:24

"用CustomSQLDialect替换配置文件中的设置"如何替换呢。。。


个人主页 | 引用回复 | 主人回复 | 返回 | 编辑 | 删除
 


» 1 »

发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.063 second(s), page refreshed 144756147 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号