让hql支持按位与运算

来源:互联网 发布:法线贴图转换软件 编辑:程序博客网 时间:2024/06/05 07:30
摘要: 目前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 0
原创粉丝点击