@Query("SELECT usr FROM User usr WHERE usr.configurable = TRUE " + "AND (" + "lower(usr.name) like lower(:filterText) OR lower(usr.userType.classType.displayName) like lower(:filterText) OR lower(usr.userType.model) like lower(:filterText)" + ")" + "") public List findByFilterText(@Param("filterText") String filterText, Sort sort);
String sql = "SELECT usr FROM User usr WHERE usr.configurable = TRUE"; for(String word : filterText.split(",")) { sql += " AND (lower(usr.name) like lower(:" + word + ") OR lower(usr.userType.classType.displayName) like lower(:" + word + ") OR lower(usr.userType.model) like lower(:" + word + "))"; }
根据JB Nizet和spring-data文档 ,您应该使用自定义接口+存储库实现。
使用方法创建接口:
public interface MyEntityRepositoryCustom { List findByFilterText(Set words); }
创建一个实现:
@Repository public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom { @PersistenceContext private EntityManager entityManager; public List findByFilterText(Set words) { // implementation below } }
在现有Repository界面中扩展新界面:
public interface MyEntityRepository extends JpaRepository, MyEntityRepositoryCustom { // other query methods }
我自己一直在寻找解决方案:“自定义”存储库接口和实现的命名非常严格(如上所述如何向Spring Data JPA添加自定义方法 )
所以,要清楚,整个代码:(但@beerbajay是对的)
自定义方法界面
public interface MyEntityRepositoryCustom { List findSpecial(); }
自定义方法实现
public class MyEntityRepositoryImpl implements MyEntityRepositoryCustom { @PersistenceContext private EntityManager em; //custom method implementation public List
“原始”存储库
@Repository public interface MyEntityRepository extends JpaRepository, MyEntityRepositoryCustom { //original methods here... do not redefine findSpecial()... }
您现在可以将“原始”存储库与新的自定义方法一起使用
@Service public class MyService { @Autowired private DataRepository r; public void doStuff() { List list = r.findSpecial(); } }