I. background
In work, the database used is MySQL, the project uses Java, and the JPA technology is used. Hibernate is used at the underlying layer. Some projects need to perform bitwise AND operations, but the hql language does not support it. This article describes how to enable our program to support bitwise AND operations.
II. Implementation
Preferred sqlfunction interface implementation
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)
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 ();
}
}
Then, expand the original dialect and register the extended functions in hibernate.
Package com. XXX. hql;
Public class customsqldialect extends org. hibernate. dialect. mysql5innodbdialect {
Public customsqldialect (){
Super ();
This. registerfunction ("bitand", new bitandfunction ());
}
}
Finally, the dialect is configured with this class.
<? 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>
The usage in hql is as follows:
From tableentity where bitand (fieldname, 1) = 0
Bitand is a self-implemented bitwise AND method.
Iii. Summary
The extended functions provided by hibernate are quite flexible. When a database feature cannot be fully utilized, you can expand the functions of Hibernate to achieve the corresponding purpose.
Enable hql to support bitwise AND OPERATION