@Query("select u from User u " + " where (u.username like concat('%',?1,'%') or ?1 is null) " + " and u.email=?2 ") List<User> findByUsernameLikeAndEmail(String username, String email);
@Query("select u from User u " + " where (u.username like ?1 or ?1 is null) " + " and u.email=?2") List<User> findByUsernameLikeAndEmail(String username, String email);
由于jpa自动提供实现,没有or ?1 is null逻辑,传参null进行调用抛出异常: 异常:org.springframework.dao.InvalidDataAccessApiUsageException: Value must not be null!; nested exception is java.lang.IllegalArgumentException: Value must not be null!
利用不同数据库中提供的函数的实现方法
mysql:contains
MYSQL中可以用CONTAINS函数,在全文索引的的字段中使用:
1 2 3 4 5 6
@Query(value = " select * from event e " + " where (?1 is null or CONTAINS(e.event_title,'?1')) " + " and (to_days(e.register_time)=to_days(?2) or ?2 is null) " + " and e.status = '1' " + " order by e.register_time desc limit ?3,?4 ",nativeQuery = true) List<Event> findAllList(String eventTitle,Timestamp registerTime,Integer pageNumber,Integer pageSize);
还可以用 find_in_set() 方法,例如:select * FROM users WHERE find_in_set('aa@email.com', emails);
oracle:instr
Oracle中提供了 instr(strSource,strTarget)函数,比使用 LIKE %关键字% 的模式效率高很多。