@k2works/claude-code-booster 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/lib/assets/docs/article/index.md +4 -1
  2. package/lib/assets/docs/article/practical-database-design/index.md +121 -0
  3. package/lib/assets/docs/article/practical-database-design/part1/chapter01.md +288 -0
  4. package/lib/assets/docs/article/practical-database-design/part1/chapter02.md +518 -0
  5. package/lib/assets/docs/article/practical-database-design/part1/chapter03.md +557 -0
  6. package/lib/assets/docs/article/practical-database-design/part2/chapter04.md +924 -0
  7. package/lib/assets/docs/article/practical-database-design/part2/chapter05.md +1627 -0
  8. package/lib/assets/docs/article/practical-database-design/part2/chapter06.md +2716 -0
  9. package/lib/assets/docs/article/practical-database-design/part2/chapter07.md +2082 -0
  10. package/lib/assets/docs/article/practical-database-design/part2/chapter08.md +2105 -0
  11. package/lib/assets/docs/article/practical-database-design/part2/chapter09.md +2031 -0
  12. package/lib/assets/docs/article/practical-database-design/part2/chapter10.md +1387 -0
  13. package/lib/assets/docs/article/practical-database-design/part2/chapter11.md +1677 -0
  14. package/lib/assets/docs/article/practical-database-design/part2/chapter12.md +1417 -0
  15. package/lib/assets/docs/article/practical-database-design/part2/chapter13.md +1434 -0
  16. package/lib/assets/docs/article/practical-database-design/part3/chapter14.md +667 -0
  17. package/lib/assets/docs/article/practical-database-design/part3/chapter15.md +1625 -0
  18. package/lib/assets/docs/article/practical-database-design/part3/chapter16.md +1915 -0
  19. package/lib/assets/docs/article/practical-database-design/part3/chapter17.md +1708 -0
  20. package/lib/assets/docs/article/practical-database-design/part3/chapter18.md +2095 -0
  21. package/lib/assets/docs/article/practical-database-design/part3/chapter19.md +1123 -0
  22. package/lib/assets/docs/article/practical-database-design/part3/chapter20.md +1031 -0
  23. package/lib/assets/docs/article/practical-database-design/part3/chapter21.md +1382 -0
  24. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter14-orm.md +991 -0
  25. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter15-orm.md +1300 -0
  26. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter16-orm.md +1166 -0
  27. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter17-orm.md +1584 -0
  28. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter18-orm.md +1183 -0
  29. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter19-orm.md +1016 -0
  30. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter20-orm.md +1753 -0
  31. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter21-orm.md +1447 -0
  32. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter22-orm.md +1878 -0
  33. package/lib/assets/docs/article/practical-database-design/part4/chapter22.md +965 -0
  34. package/lib/assets/docs/article/practical-database-design/part4/chapter23.md +2069 -0
  35. package/lib/assets/docs/article/practical-database-design/part4/chapter24.md +2439 -0
  36. package/lib/assets/docs/article/practical-database-design/part4/chapter25.md +3661 -0
  37. package/lib/assets/docs/article/practical-database-design/part4/chapter26.md +2916 -0
  38. package/lib/assets/docs/article/practical-database-design/part4/chapter27.md +3105 -0
  39. package/lib/assets/docs/article/practical-database-design/part4/chapter28.md +2697 -0
  40. package/lib/assets/docs/article/practical-database-design/part4/chapter29.md +2544 -0
  41. package/lib/assets/docs/article/practical-database-design/part4/chapter30.md +2180 -0
  42. package/lib/assets/docs/article/practical-database-design/part4/chapter31.md +1192 -0
  43. package/lib/assets/docs/article/practical-database-design/part4/chapter32.md +2101 -0
  44. package/lib/assets/docs/article/practical-database-design/part5/chapter33.md +1032 -0
  45. package/lib/assets/docs/article/practical-database-design/part5/chapter34.md +1609 -0
  46. package/lib/assets/docs/article/practical-database-design/part5/chapter35.md +1453 -0
  47. package/lib/assets/docs/article/practical-database-design/part5/chapter36.md +1292 -0
  48. package/lib/assets/docs/article/practical-database-design/part5/chapter37.md +1470 -0
  49. package/lib/assets/docs/article/practical-database-design/part5/chapter38.md +1698 -0
  50. package/lib/assets/docs/article/practical-database-design/part5/chapter39.md +2334 -0
  51. package/lib/assets/docs/article/practical-database-design/study/study2-1.md +1693 -0
  52. package/lib/assets/docs/article/practical-database-design/study/study2-2.md +1347 -0
  53. package/lib/assets/docs/article/practical-database-design/study/study2-3.md +2044 -0
  54. package/lib/assets/docs/article/practical-database-design/study/study2-4.md +2229 -0
  55. package/lib/assets/docs/article/practical-database-design/study/study2-5.md +2418 -0
  56. package/lib/assets/docs/article/practical-database-design/study/study3-1.md +2205 -0
  57. package/lib/assets/docs/article/practical-database-design/study/study3-2.md +2221 -0
  58. package/lib/assets/docs/article/practical-database-design/study/study3-3.md +2253 -0
  59. package/lib/assets/docs/article/practical-database-design/study/study3-4.md +2106 -0
  60. package/lib/assets/docs/article/practical-database-design/study/study3-5.md +2507 -0
  61. package/lib/assets/docs/article/practical-database-design/study/study4-1.md +2587 -0
  62. package/lib/assets/docs/article/practical-database-design/study/study4-2.md +2075 -0
  63. package/lib/assets/docs/article/practical-database-design/study/study4-3.md +1805 -0
  64. package/lib/assets/docs/article/practical-database-design/study/study4-4.md +1895 -0
  65. package/lib/assets/docs/article/practical-database-design/study/study4-5.md +2878 -0
  66. package/lib/assets/docs/reference//351/201/213/345/226/266/347/256/241/347/220/206.md +131 -39
  67. package/package.json +1 -1
@@ -0,0 +1,1016 @@
1
+ # 第19章:赤黒とログの設計(ORM版)
2
+
3
+ 会計システムにおけるデータ訂正方式(赤黒処理)とログ管理の設計を行います。
4
+
5
+ JPA 版では、@EntityListeners と AuditingEntityListener を使用した監査証跡の実装を行います。
6
+
7
+ ---
8
+
9
+ ## 19.1 赤黒処理の概念
10
+
11
+ 会計システムでは、一度登録したデータの「削除」や「更新」を安易に行うことはできません。監査証跡を確保しつつ、データ訂正を行う方式が必要です。
12
+
13
+ ### 赤黒処理とは
14
+
15
+ 赤黒処理とは、誤った仕訳を訂正する際に、元の仕訳を「赤伝(取消伝票)」で打ち消し、正しい仕訳を「黒伝(訂正伝票)」として新規登録する方式です。
16
+
17
+ ```plantuml
18
+ @startuml
19
+
20
+ title 赤黒処理の流れ
21
+
22
+ rectangle "元伝票(誤り)" as original {
23
+ card "仕訳番号: J0001\n【借方】現金 100,000\n【貸方】売上 100,000" as j1
24
+ }
25
+
26
+ rectangle "赤伝(取消)" as red {
27
+ card "仕訳番号: J0001R\n【借方】売上 100,000\n【貸方】現金 100,000\n※貸借を反転" as j2
28
+ }
29
+
30
+ rectangle "黒伝(訂正)" as black {
31
+ card "仕訳番号: J0002\n【借方】現金 120,000\n【貸方】売上 120,000\n※正しい金額" as j3
32
+ }
33
+
34
+ original --> red : 赤伝発行
35
+ red --> black : 黒伝発行
36
+
37
+ note bottom of red
38
+ 赤伝は元伝票の
39
+ 貸借を完全に反転
40
+ 仕訳金額の合計が
41
+ ゼロになる
42
+ end note
43
+
44
+ note bottom of black
45
+ 黒伝は正しい内容で
46
+ 新規に仕訳を起票
47
+ end note
48
+
49
+ @enduml
50
+ ```
51
+
52
+ ### 赤黒処理のメリット
53
+
54
+ | メリット | 説明 |
55
+ |---------|------|
56
+ | 監査証跡の確保 | 元の仕訳が残り、訂正履歴が追跡可能 |
57
+ | データ整合性 | 物理削除を行わないため、参照整合性が維持される |
58
+ | 会計基準準拠 | 会計原則に則った正当な訂正方法 |
59
+ | 残高の自動調整 | 赤伝により残高が自動的に訂正される |
60
+
61
+ ---
62
+
63
+ ## 19.2 赤黒処理のテーブル設計
64
+
65
+ 仕訳テーブルには、赤黒処理に必要な項目が含まれています。
66
+
67
+ ```plantuml
68
+ @startuml
69
+
70
+ entity "仕訳" as Journal {
71
+ * **仕訳伝票番号**: VARCHAR(10) <<PK>>
72
+ --
73
+ 起票日
74
+ 入力日
75
+ 仕訳伝票区分
76
+ ...
77
+ **赤伝フラグ**: SMALLINT
78
+ **赤黒伝票番号**: INTEGER
79
+ 作成日時
80
+ 更新日時
81
+ }
82
+
83
+ note right of Journal
84
+ 赤伝フラグ:
85
+ 0 = 通常(黒伝)
86
+ 1 = 赤伝(取消)
87
+
88
+ 赤黒伝票番号:
89
+ 赤伝の場合、元伝票の番号を格納
90
+ 紐付けにより履歴を追跡
91
+ end note
92
+
93
+ @enduml
94
+ ```
95
+
96
+ ---
97
+
98
+ ## 19.3 MyBatis 版との実装比較
99
+
100
+ ### データアクセス層の比較
101
+
102
+ | 機能 | MyBatis 版 | JPA 版 |
103
+ |-----|-----------|--------|
104
+ | 監査カラム設定 | 手動 / Interceptor | @EnableJpaAuditing |
105
+ | マスタ変更ログ | DB トリガー | @EntityListeners |
106
+ | ENUM 変換 | TypeHandler | AttributeConverter |
107
+ | 動的クエリ | XML `<if>` タグ | Specification パターン |
108
+ | 一括保存(Cascade) | 明示的に各テーブル INSERT | CascadeType.ALL |
109
+
110
+ ---
111
+
112
+ ## 19.4 赤黒処理サービスの実装
113
+
114
+ <details>
115
+ <summary>JournalCorrectionService.java</summary>
116
+
117
+ ```java
118
+ package com.example.accounting.application.service;
119
+
120
+ import com.example.accounting.application.port.out.JournalRepository;
121
+ import com.example.accounting.domain.model.journal.*;
122
+ import lombok.RequiredArgsConstructor;
123
+ import lombok.extern.slf4j.Slf4j;
124
+ import org.springframework.stereotype.Service;
125
+ import org.springframework.transaction.annotation.Transactional;
126
+
127
+ import java.time.LocalDate;
128
+ import java.util.ArrayList;
129
+
130
+ /**
131
+ * 赤黒処理サービス
132
+ *
133
+ * JPA 版でもビジネスロジックは MyBatis 版と同じ
134
+ * Entity の操作方法が異なる(JPA では Cascade を活用)
135
+ */
136
+ @Service
137
+ @RequiredArgsConstructor
138
+ @Slf4j
139
+ public class JournalCorrectionService {
140
+
141
+ private final JournalRepository journalRepository;
142
+ private final BalanceUpdateService balanceUpdateService;
143
+
144
+ /**
145
+ * 仕訳を赤黒訂正する
146
+ * @param originalVoucherNumber 元伝票番号
147
+ * @param correctedJournal 訂正後の仕訳(黒伝)
148
+ * @return 赤伝と黒伝の仕訳伝票番号
149
+ */
150
+ @Transactional
151
+ public CorrectionResult correctJournal(String originalVoucherNumber,
152
+ Journal correctedJournal) {
153
+ // 元伝票を取得
154
+ var original = journalRepository.findByVoucherNumber(originalVoucherNumber)
155
+ .orElseThrow(() -> new IllegalArgumentException(
156
+ "元伝票が見つかりません: " + originalVoucherNumber));
157
+
158
+ // 赤伝を作成
159
+ var redSlip = createRedSlip(original);
160
+ journalRepository.save(redSlip);
161
+ balanceUpdateService.updateBalancesForJournal(redSlip);
162
+
163
+ // 黒伝(訂正伝票)を登録
164
+ if (!correctedJournal.isBalanced()) {
165
+ throw new IllegalArgumentException("訂正仕訳の貸借が一致しません");
166
+ }
167
+ journalRepository.save(correctedJournal);
168
+ balanceUpdateService.updateBalancesForJournal(correctedJournal);
169
+
170
+ log.info("赤黒訂正完了: 元伝票={}, 赤伝={}, 黒伝={}",
171
+ originalVoucherNumber,
172
+ redSlip.getJournalVoucherNumber(),
173
+ correctedJournal.getJournalVoucherNumber());
174
+
175
+ return new CorrectionResult(
176
+ redSlip.getJournalVoucherNumber(),
177
+ correctedJournal.getJournalVoucherNumber()
178
+ );
179
+ }
180
+
181
+ /**
182
+ * 仕訳を取消する(赤伝のみ発行)
183
+ * @param voucherNumber 取消対象の仕訳伝票番号
184
+ * @return 赤伝の仕訳伝票番号
185
+ */
186
+ @Transactional
187
+ public String cancelJournal(String voucherNumber) {
188
+ var original = journalRepository.findByVoucherNumber(voucherNumber)
189
+ .orElseThrow(() -> new IllegalArgumentException(
190
+ "仕訳が見つかりません: " + voucherNumber));
191
+
192
+ // 既に赤伝が発行されているか確認
193
+ if (original.getRedSlipFlag() != null && original.getRedSlipFlag()) {
194
+ throw new IllegalStateException("この仕訳は既に取消済みです");
195
+ }
196
+
197
+ // 赤伝を作成
198
+ var redSlip = createRedSlip(original);
199
+ journalRepository.save(redSlip);
200
+ balanceUpdateService.updateBalancesForJournal(redSlip);
201
+
202
+ log.info("仕訳取消完了: 元伝票={}, 赤伝={}",
203
+ voucherNumber, redSlip.getJournalVoucherNumber());
204
+
205
+ return redSlip.getJournalVoucherNumber();
206
+ }
207
+
208
+ /**
209
+ * 赤伝を作成する
210
+ *
211
+ * JPA 版では CascadeType.ALL により、
212
+ * Journal を保存すると details も自動的に保存される
213
+ */
214
+ private Journal createRedSlip(Journal original) {
215
+ // 赤伝の仕訳伝票番号を生成(元伝票番号 + R)
216
+ var redVoucherNumber = original.getJournalVoucherNumber() + "R";
217
+
218
+ // 貸借を反転した明細を作成
219
+ var redDetails = new ArrayList<JournalDetail>();
220
+ for (var detail : original.getDetails()) {
221
+ var reversedDCDetails = new ArrayList<JournalDebitCreditDetail>();
222
+ for (var dcDetail : detail.getDebitCreditDetails()) {
223
+ var reversed = JournalDebitCreditDetail.builder()
224
+ .journalVoucherNumber(redVoucherNumber)
225
+ .lineNumber(dcDetail.getLineNumber())
226
+ .debitCreditLineNumber(dcDetail.getDebitCreditLineNumber())
227
+ // 借方→貸方、貸方→借方に反転
228
+ .debitCreditType(
229
+ dcDetail.getDebitCreditType() == DebitCreditType.DEBIT
230
+ ? DebitCreditType.CREDIT
231
+ : DebitCreditType.DEBIT)
232
+ .accountCode(dcDetail.getAccountCode())
233
+ .subAccountCode(dcDetail.getSubAccountCode())
234
+ .departmentCode(dcDetail.getDepartmentCode())
235
+ .amount(dcDetail.getAmount())
236
+ .taxType(dcDetail.getTaxType())
237
+ .taxRate(dcDetail.getTaxRate())
238
+ .build();
239
+ reversedDCDetails.add(reversed);
240
+ }
241
+
242
+ var redDetail = JournalDetail.builder()
243
+ .journalVoucherNumber(redVoucherNumber)
244
+ .lineNumber(detail.getLineNumber())
245
+ .lineSummary(detail.getLineSummary() + "(取消)")
246
+ .debitCreditDetails(reversedDCDetails)
247
+ .build();
248
+ redDetails.add(redDetail);
249
+ }
250
+
251
+ return Journal.builder()
252
+ .journalVoucherNumber(redVoucherNumber)
253
+ .postingDate(LocalDate.now())
254
+ .entryDate(LocalDate.now())
255
+ .closingEntryFlag(original.getClosingEntryFlag())
256
+ .voucherType(original.getVoucherType())
257
+ .departmentCode(original.getDepartmentCode())
258
+ .redSlipFlag(true)
259
+ .redBlackVoucherNumber(extractNumericPart(original.getJournalVoucherNumber()))
260
+ .details(redDetails)
261
+ .build();
262
+ }
263
+
264
+ private Integer extractNumericPart(String voucherNumber) {
265
+ return Integer.parseInt(voucherNumber.replaceAll("[^0-9]", ""));
266
+ }
267
+
268
+ /**
269
+ * 訂正結果
270
+ */
271
+ public record CorrectionResult(
272
+ String redSlipNumber,
273
+ String blackSlipNumber
274
+ ) {}
275
+ }
276
+ ```
277
+
278
+ </details>
279
+
280
+ ---
281
+
282
+ ## 19.5 ログ管理方式の選択
283
+
284
+ 会計システムのログ管理には、3つの方式があります。
285
+
286
+ ```plantuml
287
+ @startuml
288
+
289
+ title ログ管理方式の比較
290
+
291
+ rectangle "方式A: データ自体にログ情報を持つ" as a {
292
+ card "作成日時\n更新日時\n更新者名" as a1
293
+ }
294
+
295
+ rectangle "方式B: 赤黒処理・論理削除" as b {
296
+ card "赤伝フラグ\n赤黒伝票番号\n削除フラグ" as b1
297
+ }
298
+
299
+ rectangle "方式C: ログテーブルに保存" as c {
300
+ card "操作種別\n操作前データ\n操作後データ\n操作者" as c1
301
+ }
302
+
303
+ a -[hidden]right- b
304
+ b -[hidden]right- c
305
+
306
+ note bottom of a
307
+ 最もシンプル
308
+ 更新履歴は保持しない
309
+ JPA では @EnableJpaAuditing
310
+ end note
311
+
312
+ note bottom of b
313
+ 会計データに最適
314
+ 監査証跡を確保
315
+ end note
316
+
317
+ note bottom of c
318
+ 完全な履歴管理
319
+ マスタ更新に最適
320
+ end note
321
+
322
+ @enduml
323
+ ```
324
+
325
+ ### 推奨される組み合わせ
326
+
327
+ | データ種別 | 方式 | JPA 実装 |
328
+ |----------|------|---------|
329
+ | マスタデータ | A + C | @EnableJpaAuditing + @EntityListeners |
330
+ | トランザクションデータ | A + B | @EnableJpaAuditing + 赤黒処理 |
331
+ | サマリデータ | A | @EnableJpaAuditing のみ |
332
+
333
+ ---
334
+
335
+ ## 19.6 JPA Auditing による自動タイムスタンプ
336
+
337
+ JPA 版では、Spring Data JPA の Auditing 機能を使用して、作成日時・更新日時・作成者・更新者を自動的に設定できます。
338
+
339
+ ### Auditing 設定
340
+
341
+ <details>
342
+ <summary>AccountingApplication.java</summary>
343
+
344
+ ```java
345
+ package com.example.accounting;
346
+
347
+ import org.springframework.boot.SpringApplication;
348
+ import org.springframework.boot.autoconfigure.SpringBootApplication;
349
+ import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
350
+
351
+ @SpringBootApplication
352
+ @EnableJpaAuditing // JPA Auditing を有効化
353
+ public class AccountingApplication {
354
+ public static void main(String[] args) {
355
+ SpringApplication.run(AccountingApplication.class, args);
356
+ }
357
+ }
358
+ ```
359
+
360
+ </details>
361
+
362
+ ### AuditorAware 実装(操作者の自動設定)
363
+
364
+ <details>
365
+ <summary>AuditorAwareImpl.java</summary>
366
+
367
+ ```java
368
+ package com.example.accounting.infrastructure.config;
369
+
370
+ import org.springframework.data.domain.AuditorAware;
371
+ import org.springframework.security.core.Authentication;
372
+ import org.springframework.security.core.context.SecurityContextHolder;
373
+ import org.springframework.stereotype.Component;
374
+
375
+ import java.util.Optional;
376
+
377
+ /**
378
+ * 操作者を自動取得する AuditorAware 実装
379
+ *
380
+ * Spring Security と連携して、現在ログイン中のユーザーを取得
381
+ * @CreatedBy, @LastModifiedBy に自動設定される
382
+ */
383
+ @Component
384
+ public class AuditorAwareImpl implements AuditorAware<String> {
385
+
386
+ @Override
387
+ public Optional<String> getCurrentAuditor() {
388
+ Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
389
+
390
+ if (authentication == null || !authentication.isAuthenticated()) {
391
+ return Optional.of("system");
392
+ }
393
+
394
+ return Optional.of(authentication.getName());
395
+ }
396
+ }
397
+ ```
398
+
399
+ </details>
400
+
401
+ ### 監査情報を持つ基底 Entity
402
+
403
+ <details>
404
+ <summary>BaseEntity.java</summary>
405
+
406
+ ```java
407
+ package com.example.accounting.domain.model.common;
408
+
409
+ import jakarta.persistence.*;
410
+ import lombok.Getter;
411
+ import lombok.Setter;
412
+ import org.springframework.data.annotation.CreatedBy;
413
+ import org.springframework.data.annotation.CreatedDate;
414
+ import org.springframework.data.annotation.LastModifiedBy;
415
+ import org.springframework.data.annotation.LastModifiedDate;
416
+ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
417
+
418
+ import java.time.LocalDateTime;
419
+
420
+ /**
421
+ * 監査情報を持つ基底 Entity
422
+ *
423
+ * JPA 版では @EntityListeners と Auditing アノテーションで
424
+ * 作成日時・更新日時・作成者・更新者を自動管理
425
+ *
426
+ * MyBatis 版では手動で設定していたが、JPA 版では自動化
427
+ */
428
+ @MappedSuperclass
429
+ @EntityListeners(AuditingEntityListener.class)
430
+ @Getter
431
+ @Setter
432
+ public abstract class BaseEntity {
433
+
434
+ @CreatedDate
435
+ @Column(name = "作成日時", nullable = false, updatable = false)
436
+ private LocalDateTime createdAt;
437
+
438
+ @LastModifiedDate
439
+ @Column(name = "更新日時", nullable = false)
440
+ private LocalDateTime updatedAt;
441
+
442
+ @CreatedBy
443
+ @Column(name = "作成者", length = 50, updatable = false)
444
+ private String createdBy;
445
+
446
+ @LastModifiedBy
447
+ @Column(name = "更新者", length = 50)
448
+ private String updatedBy;
449
+ }
450
+ ```
451
+
452
+ </details>
453
+
454
+ ---
455
+
456
+ ## 19.7 マスタ変更ログテーブルの設計
457
+
458
+ ### Flyway マイグレーション
459
+
460
+ <details>
461
+ <summary>V010__create_change_log_table.sql</summary>
462
+
463
+ ```sql
464
+ -- 操作種別
465
+ CREATE TYPE 操作種別 AS ENUM ('INSERT', 'UPDATE', 'DELETE');
466
+
467
+ -- 変更ログテーブル
468
+ CREATE TABLE "変更ログ" (
469
+ "ログID" SERIAL PRIMARY KEY,
470
+ "テーブル名" VARCHAR(50) NOT NULL,
471
+ "レコードキー" VARCHAR(100) NOT NULL,
472
+ "操作種別" 操作種別 NOT NULL,
473
+ "操作前データ" JSONB,
474
+ "操作後データ" JSONB,
475
+ "操作日時" TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
476
+ "操作者" VARCHAR(50),
477
+ "操作端末" VARCHAR(100),
478
+ "備考" TEXT
479
+ );
480
+
481
+ -- インデックス
482
+ CREATE INDEX "idx_変更ログ_テーブル名" ON "変更ログ"("テーブル名");
483
+ CREATE INDEX "idx_変更ログ_レコードキー" ON "変更ログ"("レコードキー");
484
+ CREATE INDEX "idx_変更ログ_操作日時" ON "変更ログ"("操作日時");
485
+ ```
486
+
487
+ </details>
488
+
489
+ ### 変更ログ Entity
490
+
491
+ <details>
492
+ <summary>ChangeLog.java</summary>
493
+
494
+ ```java
495
+ package com.example.accounting.domain.model.audit;
496
+
497
+ import com.example.accounting.infrastructure.persistence.converter.OperationTypeConverter;
498
+ import jakarta.persistence.*;
499
+ import lombok.*;
500
+
501
+ import java.time.LocalDateTime;
502
+
503
+ /**
504
+ * 変更ログ Entity
505
+ *
506
+ * JPA 版では @Entity で定義
507
+ * @GeneratedValue で自動採番
508
+ */
509
+ @Entity
510
+ @Table(name = "変更ログ")
511
+ @Data
512
+ @Builder
513
+ @NoArgsConstructor
514
+ @AllArgsConstructor
515
+ public class ChangeLog {
516
+
517
+ @Id
518
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
519
+ @Column(name = "ログID")
520
+ private Long logId;
521
+
522
+ @Column(name = "テーブル名", length = 50, nullable = false)
523
+ private String tableName;
524
+
525
+ @Column(name = "レコードキー", length = 100, nullable = false)
526
+ private String recordKey;
527
+
528
+ @Convert(converter = OperationTypeConverter.class)
529
+ @Column(name = "操作種別", nullable = false, columnDefinition = "操作種別")
530
+ private OperationType operationType;
531
+
532
+ @Column(name = "操作前データ", columnDefinition = "JSONB")
533
+ private String beforeData;
534
+
535
+ @Column(name = "操作後データ", columnDefinition = "JSONB")
536
+ private String afterData;
537
+
538
+ @Column(name = "操作日時", nullable = false)
539
+ private LocalDateTime operatedAt;
540
+
541
+ @Column(name = "操作者", length = 50)
542
+ private String operatedBy;
543
+
544
+ @Column(name = "操作端末", length = 100)
545
+ private String operatedFrom;
546
+
547
+ @Column(name = "備考", columnDefinition = "TEXT")
548
+ private String remarks;
549
+
550
+ @PrePersist
551
+ protected void onCreate() {
552
+ if (this.operatedAt == null) {
553
+ this.operatedAt = LocalDateTime.now();
554
+ }
555
+ }
556
+ }
557
+ ```
558
+
559
+ </details>
560
+
561
+ ### 操作種別 Enum と Converter
562
+
563
+ <details>
564
+ <summary>OperationType.java と OperationTypeConverter.java</summary>
565
+
566
+ ```java
567
+ package com.example.accounting.domain.model.audit;
568
+
569
+ /**
570
+ * 操作種別 Enum
571
+ */
572
+ public enum OperationType {
573
+ INSERT,
574
+ UPDATE,
575
+ DELETE
576
+ }
577
+ ```
578
+
579
+ ```java
580
+ package com.example.accounting.infrastructure.persistence.converter;
581
+
582
+ import com.example.accounting.domain.model.audit.OperationType;
583
+ import jakarta.persistence.AttributeConverter;
584
+ import jakarta.persistence.Converter;
585
+
586
+ /**
587
+ * 操作種別 ↔ PostgreSQL ENUM 変換
588
+ */
589
+ @Converter(autoApply = true)
590
+ public class OperationTypeConverter implements AttributeConverter<OperationType, String> {
591
+
592
+ @Override
593
+ public String convertToDatabaseColumn(OperationType attribute) {
594
+ return attribute != null ? attribute.name() : null;
595
+ }
596
+
597
+ @Override
598
+ public OperationType convertToEntityAttribute(String dbData) {
599
+ return dbData != null ? OperationType.valueOf(dbData) : null;
600
+ }
601
+ }
602
+ ```
603
+
604
+ </details>
605
+
606
+ ---
607
+
608
+ ## 19.8 EntityListener によるマスタ変更ログの自動記録
609
+
610
+ JPA 版では @EntityListeners を使用して、Entity のライフサイクルイベントをフックし、変更ログを自動的に記録できます。
611
+
612
+ <details>
613
+ <summary>ChangeLogListener.java</summary>
614
+
615
+ ```java
616
+ package com.example.accounting.infrastructure.persistence.listener;
617
+
618
+ import com.example.accounting.domain.model.audit.ChangeLog;
619
+ import com.example.accounting.domain.model.audit.OperationType;
620
+ import com.example.accounting.infrastructure.persistence.repository.ChangeLogJpaRepository;
621
+ import com.fasterxml.jackson.core.JsonProcessingException;
622
+ import com.fasterxml.jackson.databind.ObjectMapper;
623
+ import jakarta.persistence.*;
624
+ import lombok.extern.slf4j.Slf4j;
625
+ import org.springframework.beans.factory.annotation.Autowired;
626
+ import org.springframework.security.core.context.SecurityContextHolder;
627
+ import org.springframework.stereotype.Component;
628
+
629
+ import java.time.LocalDateTime;
630
+
631
+ /**
632
+ * マスタ変更ログを自動記録する EntityListener
633
+ *
634
+ * JPA 版では @EntityListeners で Entity のライフサイクルをフック
635
+ * MyBatis 版では DB トリガーで実装していた機能を Java コードで実現
636
+ */
637
+ @Component
638
+ @Slf4j
639
+ public class ChangeLogListener {
640
+
641
+ private static ChangeLogJpaRepository changeLogRepository;
642
+ private static ObjectMapper objectMapper;
643
+
644
+ @Autowired
645
+ public void setChangeLogRepository(ChangeLogJpaRepository repository) {
646
+ ChangeLogListener.changeLogRepository = repository;
647
+ }
648
+
649
+ @Autowired
650
+ public void setObjectMapper(ObjectMapper mapper) {
651
+ ChangeLogListener.objectMapper = mapper;
652
+ }
653
+
654
+ @PostPersist
655
+ public void postPersist(Object entity) {
656
+ saveChangeLog(entity, OperationType.INSERT, null, entity);
657
+ }
658
+
659
+ @PostUpdate
660
+ public void postUpdate(Object entity) {
661
+ saveChangeLog(entity, OperationType.UPDATE, null, entity);
662
+ }
663
+
664
+ @PostRemove
665
+ public void postRemove(Object entity) {
666
+ saveChangeLog(entity, OperationType.DELETE, entity, null);
667
+ }
668
+
669
+ private void saveChangeLog(Object entity, OperationType operationType,
670
+ Object beforeData, Object afterData) {
671
+ try {
672
+ String tableName = getTableName(entity);
673
+ String recordKey = getRecordKey(entity);
674
+ String beforeJson = beforeData != null ? objectMapper.writeValueAsString(beforeData) : null;
675
+ String afterJson = afterData != null ? objectMapper.writeValueAsString(afterData) : null;
676
+
677
+ var changeLog = ChangeLog.builder()
678
+ .tableName(tableName)
679
+ .recordKey(recordKey)
680
+ .operationType(operationType)
681
+ .beforeData(beforeJson)
682
+ .afterData(afterJson)
683
+ .operatedAt(LocalDateTime.now())
684
+ .operatedBy(getCurrentUser())
685
+ .build();
686
+
687
+ changeLogRepository.save(changeLog);
688
+
689
+ log.debug("変更ログ記録: table={}, key={}, operation={}",
690
+ tableName, recordKey, operationType);
691
+
692
+ } catch (JsonProcessingException e) {
693
+ log.error("変更ログの JSON 変換に失敗しました", e);
694
+ }
695
+ }
696
+
697
+ private String getTableName(Object entity) {
698
+ Table tableAnnotation = entity.getClass().getAnnotation(Table.class);
699
+ return tableAnnotation != null ? tableAnnotation.name() : entity.getClass().getSimpleName();
700
+ }
701
+
702
+ private String getRecordKey(Object entity) {
703
+ return entity.toString();
704
+ }
705
+
706
+ private String getCurrentUser() {
707
+ var authentication = SecurityContextHolder.getContext().getAuthentication();
708
+ return authentication != null ? authentication.getName() : "system";
709
+ }
710
+ }
711
+ ```
712
+
713
+ </details>
714
+
715
+ ### EntityListener を使用する Entity
716
+
717
+ ```java
718
+ // Account Entity に @EntityListeners を追加
719
+ @Entity
720
+ @Table(name = "勘定科目マスタ")
721
+ @EntityListeners(ChangeLogListener.class) // 変更ログを自動記録
722
+ @Data
723
+ @Builder
724
+ @NoArgsConstructor
725
+ @AllArgsConstructor
726
+ public class Account extends BaseEntity {
727
+ // ... 既存のフィールド
728
+ }
729
+ ```
730
+
731
+ ---
732
+
733
+ ## 19.9 変更ログリポジトリの実装
734
+
735
+ ### JpaRepository と Specification
736
+
737
+ <details>
738
+ <summary>ChangeLogJpaRepository.java</summary>
739
+
740
+ ```java
741
+ package com.example.accounting.infrastructure.persistence.repository;
742
+
743
+ import com.example.accounting.domain.model.audit.ChangeLog;
744
+ import com.example.accounting.domain.model.audit.OperationType;
745
+ import org.springframework.data.jpa.repository.JpaRepository;
746
+ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
747
+ import org.springframework.data.jpa.repository.Query;
748
+ import org.springframework.data.repository.query.Param;
749
+ import org.springframework.stereotype.Repository;
750
+
751
+ import java.time.LocalDateTime;
752
+ import java.util.List;
753
+
754
+ /**
755
+ * 変更ログ JpaRepository
756
+ *
757
+ * JpaSpecificationExecutor を継承して動的クエリに対応
758
+ */
759
+ @Repository
760
+ public interface ChangeLogJpaRepository
761
+ extends JpaRepository<ChangeLog, Long>,
762
+ JpaSpecificationExecutor<ChangeLog> {
763
+
764
+ /**
765
+ * テーブル名とレコードキーで検索
766
+ */
767
+ List<ChangeLog> findByTableNameAndRecordKeyOrderByOperatedAtDesc(
768
+ String tableName, String recordKey);
769
+
770
+ /**
771
+ * テーブル名で検索
772
+ */
773
+ List<ChangeLog> findByTableNameOrderByOperatedAtDesc(String tableName);
774
+
775
+ /**
776
+ * 操作種別で検索
777
+ */
778
+ List<ChangeLog> findByOperationTypeOrderByOperatedAtDesc(OperationType operationType);
779
+
780
+ /**
781
+ * 期間指定で検索
782
+ */
783
+ @Query("SELECT c FROM ChangeLog c " +
784
+ "WHERE c.operatedAt BETWEEN :from AND :to " +
785
+ "ORDER BY c.operatedAt DESC")
786
+ List<ChangeLog> findByDateRange(
787
+ @Param("from") LocalDateTime from,
788
+ @Param("to") LocalDateTime to);
789
+
790
+ /**
791
+ * 操作者で検索
792
+ */
793
+ List<ChangeLog> findByOperatedByOrderByOperatedAtDesc(String operatedBy);
794
+ }
795
+ ```
796
+
797
+ </details>
798
+
799
+ ### Specification による動的クエリ
800
+
801
+ <details>
802
+ <summary>ChangeLogSpecifications.java</summary>
803
+
804
+ ```java
805
+ package com.example.accounting.infrastructure.persistence.specification;
806
+
807
+ import com.example.accounting.domain.model.audit.ChangeLog;
808
+ import com.example.accounting.domain.model.audit.OperationType;
809
+ import org.springframework.data.jpa.domain.Specification;
810
+
811
+ import java.time.LocalDateTime;
812
+
813
+ /**
814
+ * 変更ログ検索用 Specification
815
+ *
816
+ * JPA 版では Specification パターンで動的クエリを構築
817
+ * MyBatis 版では XML の <if> タグで動的 SQL を構築していた
818
+ */
819
+ public class ChangeLogSpecifications {
820
+
821
+ public static Specification<ChangeLog> tableNameEquals(String tableName) {
822
+ return (root, query, cb) ->
823
+ tableName == null ? null : cb.equal(root.get("tableName"), tableName);
824
+ }
825
+
826
+ public static Specification<ChangeLog> recordKeyEquals(String recordKey) {
827
+ return (root, query, cb) ->
828
+ recordKey == null ? null : cb.equal(root.get("recordKey"), recordKey);
829
+ }
830
+
831
+ public static Specification<ChangeLog> operationTypeEquals(OperationType operationType) {
832
+ return (root, query, cb) ->
833
+ operationType == null ? null : cb.equal(root.get("operationType"), operationType);
834
+ }
835
+
836
+ public static Specification<ChangeLog> operatedAtAfter(LocalDateTime from) {
837
+ return (root, query, cb) ->
838
+ from == null ? null : cb.greaterThanOrEqualTo(root.get("operatedAt"), from);
839
+ }
840
+
841
+ public static Specification<ChangeLog> operatedAtBefore(LocalDateTime to) {
842
+ return (root, query, cb) ->
843
+ to == null ? null : cb.lessThanOrEqualTo(root.get("operatedAt"), to);
844
+ }
845
+
846
+ public static Specification<ChangeLog> operatedByEquals(String operatedBy) {
847
+ return (root, query, cb) ->
848
+ operatedBy == null ? null : cb.equal(root.get("operatedBy"), operatedBy);
849
+ }
850
+ }
851
+ ```
852
+
853
+ </details>
854
+
855
+ ---
856
+
857
+ ## 19.10 変更ログリポジトリのテスト
858
+
859
+ <details>
860
+ <summary>ChangeLogRepositoryTest.java</summary>
861
+
862
+ ```java
863
+ package com.example.accounting.infrastructure.persistence.repository;
864
+
865
+ import com.example.accounting.application.port.out.ChangeLogRepository;
866
+ import com.example.accounting.domain.model.audit.ChangeLog;
867
+ import com.example.accounting.domain.model.audit.OperationType;
868
+ import org.junit.jupiter.api.*;
869
+ import org.springframework.beans.factory.annotation.Autowired;
870
+ import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
871
+ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
872
+ import org.springframework.context.annotation.Import;
873
+ import org.springframework.test.context.DynamicPropertyRegistry;
874
+ import org.springframework.test.context.DynamicPropertySource;
875
+ import org.testcontainers.containers.PostgreSQLContainer;
876
+ import org.testcontainers.junit.jupiter.Container;
877
+ import org.testcontainers.junit.jupiter.Testcontainers;
878
+
879
+ import java.time.LocalDateTime;
880
+
881
+ import static org.assertj.core.api.Assertions.*;
882
+
883
+ /**
884
+ * 変更ログリポジトリのテスト
885
+ */
886
+ @DataJpaTest
887
+ @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
888
+ @Testcontainers
889
+ @Import(ChangeLogRepositoryImpl.class)
890
+ @DisplayName("変更ログリポジトリ")
891
+ class ChangeLogRepositoryTest {
892
+
893
+ @Container
894
+ static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16")
895
+ .withDatabaseName("testdb")
896
+ .withUsername("test")
897
+ .withPassword("test");
898
+
899
+ @DynamicPropertySource
900
+ static void configureProperties(DynamicPropertyRegistry registry) {
901
+ registry.add("spring.datasource.url", postgres::getJdbcUrl);
902
+ registry.add("spring.datasource.username", postgres::getUsername);
903
+ registry.add("spring.datasource.password", postgres::getPassword);
904
+ }
905
+
906
+ @Autowired
907
+ private ChangeLogRepository changeLogRepository;
908
+
909
+ @Nested
910
+ @DisplayName("登録")
911
+ class Insert {
912
+
913
+ @Test
914
+ @DisplayName("変更ログを登録できる")
915
+ void canInsertChangeLog() {
916
+ // Arrange
917
+ var changeLog = ChangeLog.builder()
918
+ .tableName("勘定科目マスタ")
919
+ .recordKey("11100")
920
+ .operationType(OperationType.INSERT)
921
+ .afterData("{\"勘定科目コード\":\"11100\",\"勘定科目名\":\"現金\"}")
922
+ .operatedBy("admin")
923
+ .build();
924
+
925
+ // Act
926
+ changeLogRepository.save(changeLog);
927
+
928
+ // Assert
929
+ assertThat(changeLog.getLogId()).isNotNull();
930
+ var result = changeLogRepository.findById(changeLog.getLogId());
931
+ assertThat(result).isPresent();
932
+ assertThat(result.get().getTableName()).isEqualTo("勘定科目マスタ");
933
+ assertThat(result.get().getOperationType()).isEqualTo(OperationType.INSERT);
934
+ }
935
+ }
936
+
937
+ @Nested
938
+ @DisplayName("検索")
939
+ class Search {
940
+
941
+ @Test
942
+ @DisplayName("テーブル名とレコードキーで検索できる")
943
+ void canFindByTableNameAndRecordKey() {
944
+ // Act
945
+ var result = changeLogRepository.findByTableNameAndRecordKey(
946
+ "勘定科目マスタ", "11100");
947
+
948
+ // Assert
949
+ assertThat(result).allMatch(log ->
950
+ log.getTableName().equals("勘定科目マスタ") &&
951
+ log.getRecordKey().equals("11100"));
952
+ }
953
+
954
+ @Test
955
+ @DisplayName("複合条件で検索できる")
956
+ void canFindByConditions() {
957
+ // Act: Specification パターンで動的クエリ
958
+ var result = changeLogRepository.findByConditions(
959
+ "勘定科目マスタ",
960
+ null,
961
+ OperationType.UPDATE,
962
+ null,
963
+ null,
964
+ null);
965
+
966
+ // Assert
967
+ assertThat(result).allMatch(log ->
968
+ log.getOperationType() == OperationType.UPDATE);
969
+ }
970
+ }
971
+ }
972
+ ```
973
+
974
+ </details>
975
+
976
+ ---
977
+
978
+ ## 19.11 まとめ:設計のポイント
979
+
980
+ ### 赤黒処理によるデータ訂正
981
+
982
+ 1. 物理削除を行わず、赤伝で打ち消し
983
+ 2. 監査証跡の確保
984
+ 3. 残高の自動調整
985
+ 4. JPA 版では CascadeType.ALL で一括保存
986
+
987
+ ### ログ管理方式の使い分け
988
+
989
+ | データ種別 | 方式 | JPA 実装 |
990
+ |----------|------|---------|
991
+ | マスタデータ | ログテーブル方式 | @EntityListeners |
992
+ | トランザクションデータ | 赤黒処理 | Cascade 保存 |
993
+ | サマリデータ | 更新日時のみ | @EnableJpaAuditing |
994
+
995
+ ### JPA Auditing による自動化
996
+
997
+ - @CreatedDate, @LastModifiedDate で日時自動設定
998
+ - @CreatedBy, @LastModifiedBy で操作者自動設定
999
+ - AuditorAware で Spring Security 連携
1000
+
1001
+ ### MyBatis 版との比較
1002
+
1003
+ | 観点 | MyBatis 版 | JPA 版 |
1004
+ |------|-----------|--------|
1005
+ | 監査カラム設定 | 手動 / Interceptor | @EnableJpaAuditing |
1006
+ | マスタ変更ログ | DB トリガー | @EntityListeners |
1007
+ | ENUM 変換 | TypeHandler | AttributeConverter |
1008
+ | 動的クエリ | XML `<if>` タグ | Specification パターン |
1009
+ | 自動採番 | useGeneratedKeys | @GeneratedValue |
1010
+ | テスト | @MybatisTest | @DataJpaTest |
1011
+
1012
+ ---
1013
+
1014
+ ## 次章予告
1015
+
1016
+ [第20章](chapter20-orm.md)では、D社(化粧品製造販売)の事例に基づいて、Seedデータを作成します。JPA 版では CommandLineRunner と @Transactional を使用したデータ投入を実装します。