Spring Data MongoDBでのZonedDateTime
データ]
-
リンク:/tag/mongodb/[MongoDB]
1.概要
Spring Data MongoDB
モジュールは、SpringプロジェクトでMongoDBデータベースと対話するときの読みやすさと使いやすさを向上させます。
-
このチュートリアルでは、MongoDBデータベースを読み書きするときの
ZonedDateTime
Javaオブジェクトの処理方法に焦点を当てます。
2.セットアップ
Spring Data MongoDBモジュールを使用するには、以下の依存関係を追加する必要があります。
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
ライブラリの最新版はhttps://search.maven.org/classic/#search%7Cga%7C1%7Cg%3A%22org.springframework.data%22%20AND%20a%3A%22spring-data-にあります。 mongodb%22[ここ]。
Action
というモデルクラスを(
ZonedDateTime
属性で)定義しましょう。
@Document
public class Action {
@Id
private String id;
private String description;
private ZonedDateTime time;
//constructor, getters and setters
}
MongoDBと対話するために、
MongoRepository
を拡張するインターフェースも作成します。
public interface ActionRepository extends MongoRepository<Action, String> { }
それでは、
Action
オブジェクトをMongoDBに挿入し、それが正しい時刻で保存されたことを表明するテストを定義しましょう。 MongoDBの
Date
型の精度はミリ秒なので、アサート評価では、ナノ秒の情報を削除しています。
@Test
public void givenSavedAction__TimeIsRetrievedCorrectly() {
String id = "testId";
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
actionRepository.save(new Action(id, "click-action", now));
Action savedAction = actionRepository.findById(id).get();
Assert.assertEquals(now.withNano(0), savedAction.getTime().withNano(0));
}
テストを実行すると、箱から出して次のエラーが発生します。
org.bson.codecs.configuration.CodecConfigurationException:
Can't find a codec for class java.time.ZonedDateTime
-
Spring Data MongoDBには
ZonedDateTime
コンバータが定義されていません。
3. MongoDBコンバーター
MongoDBから読み取るためのコンバーターとそれに書き込むためのコンバーターを定義することで、(すべてのモデルにわたって)
ZonedDateTime
オブジェクトを処理できます。
読むために、
Date
オブジェクトから
ZonedDateTime
オブジェクトに変換しています。次の例では、
Date
オブジェクトにゾーン情報が格納されていないため、
ZoneOffset.UTC
を使用します。
public class ZonedDateTimeReadConverter implements Converter<Date, ZonedDateTime> {
@Override
public ZonedDateTime convert(Date date) {
return date.toInstant().atZone(ZoneOffset.UTC);
}
}
次に、
ZonedDateTime
オブジェクトから
Date
オブジェクトに変換します。必要に応じてゾーン情報を別のフィールドに追加することができます。
public class ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, Date> {
@Override
public Date convert(ZonedDateTime zonedDateTime) {
return Date.from(zonedDateTime.toInstant());
}
}
Date
オブジェクトはゾーンオフセットを格納しないため、この例では
UTC
を使用します。
__ZonedDateTimeReadConverter
と
ZonedDateTimeWriteConverterが
MongoCustomConversions
に追加されたので、テストは成功します。
保存されたオブジェクトの簡単な印刷はこのようになります。
Action{id='testId', description='click', time=2018-11-08T08:03:11.257Z}
MongoDBコンバーターの登録方法の詳細については、https://www.baeldung.com/spring-data-mongodb-index-annotations-converter[このチュートリアル]を参照してください。
4.結論
このクイック記事では、JavaのZonedDateTimeオブジェクトを処理するためのMongoDBコンバーターの作成方法を説明しました。
これらすべてのスニペットの実装はhttps://github.com/eugenp/tutorials/tree/master/persistence-modules/spring-data-mongodb[over on GitHub]にあります。