Spring Data JPA を使って単純な OR 検索と 少しだけ複雑な OR 検索をする方法をまとめます。
Entity
DB のテーブルと結びつく Entity がこのようになっているとします。
@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);
}
};
}
}
}
単純な OR 検索
WHERE user_id = 1 OR user_id = 2;
usersRepository.findAll(Specification
.where(UsersSpecifications.userIdContains(1))
.or(UsersSpecifications.userIdContains(2)));
少し複雑な OR 検索
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))));