4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Data Jpa Specification で OR 検索する

Last updated at Posted at 2019-04-07

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))));
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?