我正在嘗試在規范中運行一些位操作,但檔案很少。
例如,我有一個tb_user帶有 bit(32) 欄位的表roles。我正在嘗試搜索具有特定翻轉位(位 = 1)的記錄。假設我搜索 b'1011' 并且結果應該回傳所有翻轉了 bit0 或 bit1 或 bit3 的記錄。如果我搜索 b'0011' 并且結果應該回傳具有 bit0、bit1 翻轉的記錄。
我怎樣才能在 JPA 規范中做到這一點?
public static Specification<TbUser> role(Integer roles) {
return ObjectUtils.isEmpty(roles) ?
(root, query, builder) -> builder.conjunction() :
(root, query, builder) -> {
// How do I run the bit operations?
}
}
uj5u.com熱心網友回復:
我看不到按位 AND 是 SQL 的一部分;JPA/JPQL 被撰寫為與資料庫無關,因此不會在其中內置特定于資料庫的支持(Transact-SQL?)。
JPA 3 規范部分“4.6.17.3”有一個“FUNCTION”運算子,可用于將“&”應用于您的引數。Criteria api 有一個“函式”方法可以操作相同,但您必須提供預期的回傳型別才能在大于運算式中使用它。就像是
Expression<Integer> bitwiseAnd = builder.function("&", Integer.class, root.get("role"), 4);
builder.greaterThan(bitwiseAnd, 0);
uj5u.com熱心網友回復:
在我的盡頭
builder.function("&", Integer.class, root.get("role"), 4);
會觸發錯誤
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '&(tbvehicle0_.perception, 524290)>0 or &(tbvehicle0_.perception, 524290)<0)' at line 1
所以我不能在規范中直接使用“&”。
另一種有效的方法如下:
// customize a MySQL5Dialect with new registered function
public class ExtendedMySQL5Dialect extends MySQL5Dialect {
public ExtendedMySQL5Dialect() {
super();
// added bitwise operators
registerFunction("bit_and", new SQLFunctionTemplate(IntegerType.INSTANCE, "(?1 & ?2)"));
registerFunction("bit_or", new SQLFunctionTemplate(IntegerType.INSTANCE, "(?1 | ?2)"));
registerFunction("bit_xor", new SQLFunctionTemplate(IntegerType.INSTANCE, "(?1 ^ ?2)"));
}
}
// change your yaml or property file
spring:
application:
name: user-service
jpa:
hibernate:
ddl-auto: update
database-platform: com.package.path.ExtendedMySQL5Dialect
//implementation of specification
public static Specification<TbUser> role(Integer roles) {
return ObjectUtils.isEmpty(roles) ?
(root, query, builder) -> builder.conjunction() :
(root, query, builder) -> {
Expression<Integer> bitwiseAnd = builder.function("bit_and", Integer.class, root.get("role"), 4);
return builder.greaterThan(bitwiseAnd, 0);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481183.html
