在使用Jpa 查询,想要实现如下sql:
SELECT *
FROM table WHERE id =... AND (already_used = TRUE OR expire_date < ...)
原使用:findByIdAndAlreadUsedTrueOrExpireDateBefore()方法,发现jpa实现的是
where id =? and already_used = true or expire_date < ?
并不是我想要的。
解决方法:
1、使用@Query注解写原生sql来实现,但是如果有分页就比较麻烦
2、将 A and (B or C) 拆分成 A and B or A and C
findByIdAndAlreadUsedTrueOrExpireDateBefore()
===>
findByIdAndAlreadUsedTrueOrIdAndExpireDateBefore()
即可,示例如下:
public class Girls {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private long classes;
private Boolean hasBF;
private int age;
private String cupSize;
private String name;
}
public interface GirlsDao extends JpaRepository<Girls,Long> {
List findByClassesAndHasBFTrueOrCupSize(long classes,String cupSize);
List findByClassesAndHasBFTrueOrClassesAndCupSize(long classes0,long classes1,String cupSize);
}
测试:查找同一个classes下只要hasBF ==True 或cupSize==”B”中满足其中一个条件即可的数据
方法一:
@Test
public void test(){
List girls = girlsDao.findByClassesAndHasBFTrueOrCupSize(12, "B");
girls.forEach(System.out::println);
}
结果如下:
Hibernate: select girls0_.id as id1_0_, girls0_.age as age2_0_, girls0_.classes as classes3_0_, girls0_.cup_size as cup_size4_0_, girls0_.hasbf as hasbf5_0_, girls0_.name as name6_0_ from girls girls0_ where girls0_.classes=? and girls0_.hasbf=1 or girls0_.cup_size=?
Girls{id=1, classes=12, hasBF=true, age=18, cupSize='B', name='XI'}
Girls{id=2, classes=12, hasBF=false, age=17, cupSize='B', name='HE'}
Girls{id=3, classes=12, hasBF=true, age=18, cupSize='C', name='HH'}
Girls{id=4, classes=13, hasBF=true, age=16, cupSize='B', name='XX'}
方法二:
@Test
public void contextLoads() {
List girls = girlsDao.findByClassesAndHasBFTrueOrClassesAndCupSize(12, 12, "B");
girls.forEach(System.out::println);
}
结果如下:
Hibernate: select girls0_.id as id1_0_, girls0_.age as age2_0_, girls0_.classes as classes3_0_, girls0_.cup_size as cup_size4_0_, girls0_.hasbf as hasbf5_0_, girls0_.name as name6_0_ from girls girls0_ where girls0_.classes=? and girls0_.hasbf=1 or girls0_.classes=? and girls0_.cup_size=?
Girls{id=1, classes=12, hasBF=true, age=18, cupSize='B', name='XI'}
Girls{id=2, classes=12, hasBF=false, age=17, cupSize='B', name='HE'}
Girls{id=3, classes=12, hasBF=true, age=18, cupSize='C', name='HH'}