1.传入根据对象的属性和值查询
public List<User> getListByOrgId(String orgId) {
//1.实例化user对象
User user = new User();
//2.设置机构主键
user.setUniid(orgId);
//3.获取Example对象
Example<User> ex = Example.of(user);
//4.执行查询
return userDao.findAll(ex);
}
执行的sql为:
Hibernate: select user0_.useid as useid1_3_, user0_.acctyp where user0_.uniid=?
2.Specification类的复杂查询
在dao中声明方法
public interface UserDao extends JpaRepository<User, Integer> {
List<User> findAll(Specification<User> spec);
}
一、and
public List<User> findUserComplex(String viuseacc,String viusepwd) {
Specification<User> sp = new Specification<User>() {
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
//1.1.设置账号为查询的字段
Path<String> useacc = root.get("useacc");
//1.2设置密码为查询的字段
Path<String> usepwd = root.get("usepwd");
//2.1拼装条件
Predicate p1 = cb.equal(useacc,viuseacc);
Predicate p2 = cb.equal(usepwd,viusepwd);
Predicate p3 =cb.and(p1,p2);
list.add(p3);
return p3;
}
};
List<User> user=userDao.findAll(sp);
System.out.println("user~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+user);
return user;
}
二、or
public List<User> findUserComplex(String viuseacc,String viusepwd) {
System.out.println("useacc!!!!!!!!!!!!!"+viuseacc);
System.out.println("usepwd!!!!!!!!!!!"+viusepwd);
Specification<User> sp = new Specification<User>() {
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
//1.1.设置账号为查询的字段
Path<String> useacc = root.get("useacc");
//1.2设置密码为查询的字段
Path<String> usepwd = root.get("usepwd");
//2.1拼装条件
Predicate p1 = cb.equal(useacc,viuseacc);
Predicate p2 = cb.equal(usepwd,viusepwd);
Predicate p3 =cb.or(p1,p2);
list.add(p3);
return p3;
}
};
List<User> user=userDao.findAll(sp);
System.out.println("user~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+user);
return user;
三、like
public List<User> findUserComplex(String viuseacc,String viusepwd) {
System.out.println("useacc!!!!!!!!!!!!!"+viuseacc);
System.out.println("usepwd!!!!!!!!!!!"+viusepwd);
Specification<User> sp = new Specification<User>() {
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<Predicate>();
//1.1.设置账号为查询的字段
Path<String> useacc = root.get("useacc");
//1.2设置密码为查询的字段
Path<String> usepwd = root.get("usepwd");
//2.1拼装条件
Predicate p1 = cb.like(useacc,viuseacc);
Predicate p2 = cb.equal(usepwd,viusepwd);
Predicate p3 =cb.or(p1,p2);
list.add(p3);
return p3;
}
};
List<User> user=userDao.findAll(sp);
System.out.println("user~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+user);
return user;