| この記事の要点 |
|---|
|
エラーの状況
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アノテーションとは
最近更新/作成されたページ
- プロジェクトをTomcatプロジェクトとして認識させる方法 2026-10-07 22:32:50
- MySQLの1366 Incorrect string value|Laravelの文字コード・絵文字エラー 2026-10-07 21:54:03
- curlの証明書ホスト名不一致|旧エラー51・現行60の確認と対処 2026-10-07 21:54:03
- LaravelのMassAssignmentException|fillableの原因と安全な対処 2026-10-07 21:54:03
- Eclipse で Tomcat の起動ログがコンソールに出ない時の確認手順 2026-10-07 21:54:02
- MySQLにおける中央値(Median)の導き方(バージョン8未満) 2026-10-07 13:49:45
- getInputForward 2026-10-07 13:41:15
- JSONから配列に変換 2026-10-07 13:41:15
- ビューから値をモデルに格納しコントローラーで受け取る方法 2026-10-07 13:23:41
- Laravelのテーブル作成と定義変更|マイグレーション・up/down・注意点 2026-10-07 13:23:41
- NumPy 配列に要素を追加する方法 (append / concatenate) 2026-10-07 13:23:41
- MariaDB・MySQLで現在日時を取得する方法|NOW・タイムゾーン・保存型 2026-10-07 13:13:36
- 【django】テンプレートで定数を使用する方法 2026-10-07 13:10:15
- Spring BootにおけるApplication.propertiesの環境依存設定の分割方法 2026-10-07 12:09:35
- Not supported for DML operations【Springエラー】 2026-10-07 11:09:38