2

Oracle テーブルの 1 つが次のようになります。これを変更するオプションはありません。

REPORTING_PERIOD | REPORTING_DATE (Oracle DATE type)
-------------------------------
1140               01-FEB-12
1139               01-JAN-12

次のような JPA エンティティ (プロバイダーとして Hibernate を使用):

@Column(name="REPORTING_PERIOD")
private long reportingPeriod;

@Temporal( TemporalType.DATE)
@Column(name="REPORT_DATE")
private Date reportDate; //java.util.Date

それでは、単体テストを行ってみましょう: (リポジトリに Spring Data JPA を使用しています) 以下の行は、REPORTING_PERIOD 列で DB をクエリします。

ReportingPeriod period1 = reportingPeriodRepository.findByMaxReportingPeriod();
assertNotNull(period1); // works fine and entity is fetched
System.out.println(period1.getReportDate());

SOP の出力は2012-02-01です - データベース01-FEB-12 の値からの自動変換に注意してください

ここで、以下で行っているように、「01-FEB-12」を使用して日付で直接クエリを実行すると、結果が得られません。

ReportingPeriod period2 = reportingPeriodRepository.findByReportDate(period1.getReportDate());
assertNotNull(period2);

前のステートメントで正常に取得できたのと同じエンティティの日付フィールドを使用していることに注意してください。

これも機能しません:

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
ReportingPeriod period3 = reportingPeriodRepository.findByReportDate(df.parse("2012-02-01"));
assertNotNull(period3);

db の値が 01-FEB-12 の場合、パラメータとして REPORTING_DATE を使用して (HQL を使用しても問題ありません) クエリを実行する方法についてのヘルプをいただければ幸いです。

4

1 に答える 1

2

ReportingPeriodRepository.findByMaxReportingPeriod(); で結果を取得する際に、明示的な日付形式の変換があると思います。

したがって、データベース形式と同じ形式を使用してデータを取得するかどうかを確認できます

変化する

DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
ReportingPeriod period3 = reportingPeriodRepository.findByReportDate(df.parse("2012-02-01"))

DateFormat df = new SimpleDateFormat("dd-MMM-yy"); 
ReportingPeriod period3 = reportingPeriodRepository.findByReportDate(df.parse("01-FEB-12"))
于 2012-04-29T08:09:41.810 に答える