📜 ⬆️ ⬇️

Hibernate and bit operations

As it turned out, Hibernate does not accept bit operations under the hql query conditions. For example, “from Events where type & mask <> 0” generates an exception of the parser, there are no bit operations in the documentation either. However, do not despair.


public class BitwiseAndFunction extends StandardSQLFunction
implements SQLFunction {

public BitwiseAndFunction( String name) {
super(name);
}

public BitwiseAndFunction( String name, Type type) {
super(name, type);
}

public String render( List args, SessionFactoryImplementor factory)
throws QueryException {

if (args.size() != 2) {
throw new IllegalArgumentException( "the function must be passed 2 arguments" );
}

StringBuffer buffer = new StringBuffer(args. get (0).toString());
buffer.append( " & " ).append(args. get (1));
return buffer.toString();
}
}


* This source code was highlighted with Source Code Highlighter .


Dalle needs to create a dialect, inheriting from the current:

public class MySQLDialectFixed extends MySQL5Dialect {

public MySQLDialectFixed() {
super();
registerFunction( "bitwise_and" , new BitwiseAndFunction( "bitwise_and" , Hibernate.INTEGER));
}
}


* This source code was highlighted with Source Code Highlighter .

')
Unfortunately, using type & mask <> 0 will not work anyway, only bitwise_and(type, mask) <> 0 . However, the SQL query will look right.

Source: https://habr.com/ru/post/50260/


All Articles