LoginSignup
3
1

More than 3 years have passed since last update.

【Spring Data JPA】deleteの自動実装されるメソッドでAnd条件は使えるか

Last updated at Posted at 2020-09-14

概要

【Spring Data JPA】自動実装されるメソッドの命名ルールの記事にある通り、JPAではrepositoryの命名規則に合うメソッでを定義することで、クエリを自動生成してくれる機能があります。今回はその自動生成でdeleteの時にAnd条件を使えるかという話です。

deleteについて

結論

And条件は使えました。試してはいませんが、おそらく他の条件も使えると思います。
ただ、複雑な条件はNativeQueryとかで実装した方が良いと思います。。

実装サンプル

Entity

UserPost.java

@Entity
@Table(name = "user_posts")
public class UserPost {
  @Id
  private long id;
  private long userId;
  private String contents;

  public long getId() {
    return this.id;
  }
  public void setId(long id) {
    this.id = id;
  }

  public long getUserId() {
    return this.userId;
  }
  public void setUserId(long userId) {
    this.userId = userId;
  }

  public String getContents() {
    return this.contents;
  }
  public void setContents(String contents) {
    this.contents = contents;
  }
}

Repository

UserPostRepository.java

@Repository
public interface UserPostRepository extends JpaRepository<UserPost, String> {
    // idとuserIdをAnd条件で指定してレコード削除
    void deleteByIdAndUserId(long id, long userId);
}

3
1
2

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
3
1