Bitwise AND computation (&) are supported in many databases. Unfortunately, Hibernate 3 does not support & computation in hql. If you write the following hql:
Where a. ID &: mask =: Target
Hibernate reports the following error: exception: Unexpected CHAR :'&'.
How can this problem be solved? The method is to use the custom sqlfunction supported by hibernate to define a bitand (a, B) sqlfunction, and then write an interpreter to generate an SQL statement of A & B.
To implement a custom sqlfunction, you must implement the sqlfunction interface:
Package com. js. dialect;
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;
/**
* <P>
* Title: bitandfunction
* </P>
* <P>
* Description:
* </P>
*
* @ Author JS
* @ Version
* @ Since
*/
Public class bitandfunction implements sqlfunction {
Public type getreturntype (type, mapping ){
Return hibernate. Integer;
}
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 ();
}
}
Then, a custom customsqldialect is derived based on the database dialect used:
Package com. js. dialect;
Import org. hibernate. dialect. mysqlinnodbdialect;
/**
* <P>
* Title: customsqldialect
* </P>
* <P>
* Description:
* </P>
*
* @ Author JS
* @ Version
* @ Since
*/
Public class customsqldialect extends mysqlinnodbdialect {
/**
*
*/
Public customsqldialect (){
Super ();
Registerfunction ("bitand", new bitandfunction ());
}
}
Set the function name to bitand. The parameters and returned values are both hibernate. long. Now, replace the settings in the configuration file with customsqldialect, and then modify hql:
Where bitand (A. ID,: mask) =: Target
Compile, run, observe the SQL output of hibernate, And the execution fails! Do not know "bitand "!