让hql支持按位与运算

摘要: 目前hibernate不支持按位与运算,近期的项目又需要这样的操作,好在hibernate提供了相关的扩展功能,能自己实现相关的操作

一、背景

   工作中,使用的数据库为MySQL,项目使用的语言为java,采用了JPA技术,底层用的是hibernate,项目中有些需要进行按位与运算,但是hql语言确不支持,该文章描述了如何让我们的程序支持按位与的操作

二、实现

     首选实现SQLFunction接口


  

package com.XXXX.hql;


import java.util.List;


import org.hibernate.QueryException;

import org.hibernate.dialect.function.SQLFunction;

import org.hibernate.engine.spi.Mapping;

import org.hibernate.engine.spi.SessionFactoryImplementor;

import org.hibernate.type.Type;


public class BitAndFunction implements SQLFunction {


@Override

public boolean hasArguments() {

return true;

}


@Override

public boolean hasParenthesesIfNoArguments() {

return true;

}

@Override

public Type getReturnType(Type firstArgumentType, Mapping mapping)

throws QueryException {

return org.hibernate.type.IntegerType.INSTANCE;

}

@Override

public String render(Type firstArgumentType, List arguments,

SessionFactoryImplementor factory) throws QueryException {

if(arguments.size() != 2){

 throw new IllegalArgumentException("BitAndFunction requires 2 arguments!"); 

}

return arguments.get(0).toString() + " & " + arguments.get(1).toString(); 

}

}


然后扩展原有的方言,将自己扩展的功能注册到hibernate中

package com.XXX.hql;

public class CustomSQLDialect extends org.hibernate.dialect.MySQL5InnoDBDialect {

public CustomSQLDialect() {

super();

this.registerFunction("bitand", new BitAndFunction());

}

}


最后配置方言是配置上该类


<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">

        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>

            <property name="hibernate.dialect" value="com.XXX.hql.CustomSQLDialect"/>

           <property name="hibernate.hbm2ddl.auto" value="update"/>

            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>

            <property name="hibernate.connection.charSet" value="UTF-8"/>

            <property name="hibernate.show_sql" value="true"/>

        </properties>

    </persistence-unit>

</persistence>


在hql语言中使用方式如下:

    from TableEntity where bitand(fieldname,1) =0    (ps:我自己测的使用的是bitand(fieldname,1) >0  

bitand就是自己实现的按位与的方法


三、总结

    hibernate提供的扩展功能还是相当灵活的,当数据库的一个特性不能充分发挥时,可以自己扩展hibernate的功能来达到相应的目的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值