Voici comment utiliser Spring Data JPA pour effectuer une recherche OR simple et une recherche OR légèrement plus complexe.
Entity Supposons que l'entité associée à une table DB ressemble à ceci.
@Data
@Entity
@Table(name = "users")
public class Users {
@Id
@Column(name = "user_id")
private int userId;
@Column(name = "company_id")
private int companyId;
}
Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
}
Specification
public class UsersSpecifications {
public static Specification<Users> userIdContains(
int userId) {
return new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
return cb.equal(root.get("userId"), userId);
}
};
public static Specification<Users> companyIdContains(
int companyId) {
return new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
return cb.equal(root.get("companyId"), companyId);
}
};
}
}
}
WHERE user_id = 1 OR user_id = 2;
usersRepository.findAll(Specification
.where(UsersSpecifications.userIdContains(1))
.or(UsersSpecifications.userIdContains(2)));
WHERE company_id = 3 AND (user_id = 1 OR user_id = 2);
usersRepository.findAll(Specification
.where(UsersSpecifications.companyIdContains(1))
.and(UsersSpecifications.userIdContains(1).or(UsersSpecifications.userIdContains(2))));
Recommended Posts