Here's how to use Spring Data JPA to do a simple OR search and a slightly more complex OR search.
Entity Suppose the Entity associated with the DB table looks like this.
@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