| この記事の要点 |
|---|
|
エラーの状況
org.hibernate.AnnotationException:
No identifier specified for entity: com.example.User
JPA / Hibernate のエンティティは主キーが必須で、@Id アノテーションでフィールドを 1 つ指定する必要があります。
基本的な解決
// ダメな例
@Entity
@Table(name = "users")
public class User {
private Long id; // ← @Id がない!
private String name;
}
// 修正
@Entity
@Table(name = "users")
public class User {
@Id // ← 必須
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
主キー生成戦略
| 戦略 | 説明 | 対応 DB |
|---|---|---|
IDENTITY | DB の AUTO_INCREMENT / IDENTITY 列 | MySQL / PostgreSQL / SQL Server |
SEQUENCE | DB シーケンスから取得 | Oracle / PostgreSQL / DB2 |
AUTO | DB に応じて自動選択 | 標準 |
TABLE | 専用テーブルでカウンタ管理 | すべての DB(パフォーマンス低) |
UUID | UUID 自動生成 (Hibernate 6+) | 標準 |
| 指定なし | アプリ側で値を設定 | ― |
例: 各戦略
// IDENTITY (MySQL / PostgreSQL の AUTO_INCREMENT)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// SEQUENCE (Oracle / PostgreSQL)
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_sequence", allocationSize = 1)
private Long id;
// UUID
@Id
@GeneratedValue(strategy = GenerationType.UUID) // Hibernate 6+
private UUID id;
// アプリ側で生成
@Id
private String code; // 例: "USR-2026-001" を自分でセット
複合主キー (Composite Key)
複数フィールドで主キーを構成する場合。
方法 1: @IdClass
// 別途主キークラスを定義 (equals/hashCode 必須)
public class OrderItemId implements Serializable {
private Long orderId;
private Long productId;
public OrderItemId() {}
public OrderItemId(Long orderId, Long productId) {
this.orderId = orderId;
this.productId = productId;
}
@Override
public boolean equals(Object o) { ... }
@Override
public int hashCode() { ... }
}
// エンティティで @IdClass を指定
@Entity
@IdClass(OrderItemId.class)
public class OrderItem {
@Id
private Long orderId;
@Id
private Long productId;
private int quantity;
}
方法 2: @EmbeddedId(推奨)
// 埋め込み可能クラスとして定義
@Embeddable
public class OrderItemId implements Serializable {
@Column(name = "order_id")
private Long orderId;
@Column(name = "product_id")
private Long productId;
public OrderItemId() {}
public OrderItemId(Long orderId, Long productId) {
this.orderId = orderId;
this.productId = productId;
}
@Override
public boolean equals(Object o) { ... }
@Override
public int hashCode() { ... }
}
@Entity
public class OrderItem {
@EmbeddedId
private OrderItemId id;
private int quantity;
}
// 検索
OrderItem item = repository.findById(new OrderItemId(orderId, productId)).orElseThrow();
UUID 主キーの推奨パターン
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.UUID) // Hibernate 6+
@Column(columnDefinition = "VARCHAR(36)") // または BINARY(16)
private UUID id;
}
// Hibernate 5 以前
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
@Column(columnDefinition = "char(36)")
private String id;
主キーの設計指針
- 自然キー vs 代理キー: 自然キー(メールアドレス等)より代理キー(id)が推奨。変更耐性・パフォーマンス・JOIN 効率の面で有利
- Long vs UUID: 単一 DB なら Long (連番)、分散システムなら UUID
- 複合キー: 中間テーブル以外では避ける(コードが複雑になる)
- IDENTITY の制約: バッチ INSERT で 1 件ずつ ID 取得が必要、SEQUENCE のほうが効率的
関連エラー
Multiple identifiers specified for entity:@Idを複数フィールドに付けた(複合キーの場合は@IdClass/@EmbeddedId)Cannot determine identifier from a null id: ID が null のまま永続化を試みたid to load is required for loading: find に null を渡したdetached entity passed to persist: 既に管理されたエンティティを persist しようとした
関連記事
子ページ
子ページはありません
同階層のページ
- java.lang.IllegalStateException: CGLIB is required to process @Configuration classes
- Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator
- No mapping found for HTTP request with URI ... in DispatcherServlet with name ...
- An internal error occurred during: "Building UI model". com/google/common/base/Function
- No identifier specified for entity : ...
- org.hibernate.hql.internal.ast.QuerySyntaxException: table_name is not mapped
- No compiler is provided in this environment
- java.sql.SQLException: The server time zone value ' ... ' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone
- Caused by: java.lang.RuntimeException: Executing an update/delete query
- Not supported for DML operations
- Field ... required a bean of type ... that could not be found.
- Annotation-specified bean name 'xxxController' for bean class [com.xxx.controller.xxxController] conflicts with existing, non-compatible bean definition of same name and class [com.xxx.xxxController]
- Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.
- Exception in thread "main" java.lang.UnsupportedClassVersionError
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- Git pushした変更の取消し|revert・履歴変更と保護の注意点 2026-10-15 23:49:01
- Gitでローカルを戻す前に|reset・restoreの違いと退避範囲 2026-10-15 23:49:01
- Git rebaseの使い方|対象範囲・競合解決・pushの判断 2026-10-15 22:50:59
- Git pullの使い方|取込み先・ff-only・競合とstashの注意点 2026-10-15 22:50:59
- Git pushの使い方|送信先・タグ・force-with-leaseの条件 2026-10-15 22:12:47
- Git remoteの設定・確認・削除|SSH URLとfetch/pushの違い 2026-10-15 22:12:47
- Gitリモートリポジトリの作成|初回push・既存履歴・mirrorの注意 2026-10-15 15:48:16
- Gitのuser.name・user.email設定|local/global・確認と過去履歴の注意 2026-10-15 15:30:07
- LinuxにGitをインストール|配布元・初期設定・TLSと認証の確認 2026-10-15 15:30:06
- Git導入と初回push|Linuxサーバー・Windows/macOS・SSH設定 2026-10-15 14:51:54
- Db2のCREATE INDEX|索引定義・INCLUDEと実行計画の確認 2026-10-15 14:10:22
- Db2の自動採番|IDENTITY・ID取得とRESTARTの注意点 2026-10-15 14:10:22
- 【DB2】特定スキーマの全テーブルの全カラム情報を取得する方法 2026-10-15 13:53:15
- Db2のシーケンスとIDENTITYの違い|採番とカタログの確認SQL 2026-10-15 13:53:15
- Db2で複数カラムをUPDATEする方法|SET・WHEREと更新前の値 2026-10-15 13:53:15