0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

@GeneratedValueを使用するエンティティで主キー(idなど)を持つコンストラクタを作るとエラー

Posted at

エンティティクラスでidなどの主キーに@GeneratedValueを使用する場合、JPAがIDの自動生成を管理するためデフォルトコンストラクタを必要としてエラーが発生する場合がある。

エンティティクラスで@GeneratedValueを使用する場合、以下のように対応する必要がある。

1. 全フィールドのコンストラクタを作らない

修正前
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    
    public Book(Long id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }
}

修正後

@Entity
public class Book {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;
   private String title;
   private String author;

   // デフォルトコンストラクタ(JPA 用)
   protected Book() {}

   // ID を含まないコンストラクタ
   public Book(String title, String author) {
       this.title = title;
       this.author = author;
   }
}

2. Lombok を使う場合

Lombok の @AllArgsConstructor を使うと ID を含むコンストラクタが生成されてしまうので、代わりに @NoArgsConstructor@RequiredArgsConstructor を組み合わせます
import jakarta.persistence.*;
import lombok.*;

@Entity
@Getter
@Setter
@NoArgsConstructor // デフォルトコンストラクタ
@RequiredArgsConstructor // 必須フィールドのみを持つコンストラクタ
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NonNull
    private String title;

    @NonNull
    private String author;
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?