Spring Jpa + Query-Dsl查詢使用位運算
阿新 • • 發佈:2018-12-12
本例專案原始碼地址 本文內容前提建立在自己對Jpa和hibernate有所瞭解。由於自己比較喜歡使用Gradle作為構建工具,所以專案基本都使用Gradle為例。如果本文有存在錯誤,希望大家指出說明。
準備工作
使用Spring boot作為基本環境,新增相關依賴。資料庫這裡採用Mysql
dependencies { compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('com.querydsl:querydsl-jpa:+') compileOnly('com.querydsl:querydsl-apt:+:jpa') compile 'mysql:mysql-connector-java' }
新增位運算函式
-
為hibernate建立新增位運算函式,具體方法參考 這裡 。
-
使用NumberTemplate建立位運算表示式
public abstract class BitwiseExpressions { public static NumberTemplate<Integer> bitand(Object arg1, Object arg2) { return Expressions.numberTemplate(Integer.class, "function('bitand', {0}, {1})", arg1, arg2); } public static NumberTemplate<Integer> bitor(Object arg1, Object arg2) { return Expressions.numberTemplate(Integer.class, "function('bitor', {0}, {1})", arg1, arg2); } public static NumberTemplate<Integer> bitxor(Object arg1, Object arg2) { return Expressions.numberTemplate(Integer.class, "function('bitxor', {0}, {1})", arg1, arg2); } }
使用方法
具體參考原始碼內容
animalRepo.findAll(qAnimal.name.endsWith("3").and(BitwiseExpressions.bitand(qAnimal.id, 2).eq(2)));
animalRepo.findAll(BitwiseExpressions.bitor(qAnimal.id, 2).eq(2));
animalRepo.findAll(qAnimal.age.goe(BitwiseExpressions.bitxor(qAnimal.id, 2)));