我有一個構建在 DynamoDB 之上的 Spring 應用程式。我正在嘗試撰寫一個saveFoo()將型別物件保存Foo到資料庫的存盤庫方法。該方法將從應用層呼叫。
我正在努力解決的問題是Foo該類中有特定于 Dynamo 的欄位。我不希望saveFoo()該類的客戶認為他們需要Foo使用這些欄位創建一個型別的物件。我也不希望他們嘗試自己設定這些值。
這些特定于資料庫的欄位需要公共 getter 和 setter 才能與 DynamoDB SDK 一起使用。
資料庫模型類如下所示:
@DynamoDBTable(tableName = "foo")
public class Foo {
// Fields the client should be setting
private String bar;
private String baz;
// Fields the client should not access and should not care about. They are internal fields used for DynamoDB purposes.
private Long version;
private String gsiIndexKey;
// Empty constructor needed for deserialization of data from dynamodb
public Foo() {
}
// Getters and setters for all of the above fields.
}
以及將物件保存到資料庫的存盤庫方法:
public class FooRepositoryImpl {
public Foo saveFoo(WhatClassShouldThisBe foo) {
// Code that saves a new Foo item to the database and returns it.
}
}
我目前的想法是創建一個 FooWrapper 介面,該saveFoo()方法可以將其作為引數。包裝器將允許客戶端設定他們應該控制的欄位,但不會公開與資料庫內部相關的欄位。如下所示:
/**
* Allows us restrict visibility of the Foo fields to the Application by hiding database internal fields.
**/
public interface FooWrapper {
Foo getFoo()
}
public class FooWrapperImpl implements FooWrapper {
private final Foo foo;
public FooWrapperImpl(String bar, String baz) {
foo = new Foo();
foo.setBar(bar);
foo.setBaz(baz);
}
@Override
public Foo getFoo() {
return foo;
}
}
public class FooRepositoryImpl {
public Foo saveFoo(FooWrapper fooWrapper) {
Foo foo = fooWrapper.getFoo(); // Save this item to db
// Code that saves a new Foo item to the database and returns it.
}
}
您對這種方法有何看法?有誰知道我可以嘗試一些更好的技術嗎?我不禁覺得我在這里過度設計了一些東西。
uj5u.com熱心網友回復:
僅向具有所需方法的客戶端公開介面。在內部,您可以呼叫實作的其他公共方法,但客戶端代碼不會知道它們。
如果您使用的是現代 Java,請不要將您的實作類匯出到您的模塊之外。只匯出公共介面。
您還可以保留一個介面供內部使用,該介面具有比公共 API 更多的方法。
public interface Foo {
public void setBar(String bar);
public void setBaz(String baz);
}
@DynamoDBTable(tableName = "foo")
public class FooImpl implements Foo {
// Fields the client should be setting
private String bar;
private String baz;
// Fields the client should not access and should not care about. They are internal fields used for DynamoDB purposes.
private Long version;
private String gsiIndexKey;
// Empty constructor needed for deserialization of data from dynamodb
public FooImpl() {
}
// Getters and setters for all of the above fields.
@Override
public void setBar(String bar) {
this.bar = bar;
}
@Override
public void setBaz(String baz) {
this.baz = bar;
}
// Not part of the Foo interface
public void setVersion(Long version) {
this.version = version;
}
public void setGsiIndexKey(String indexKey) {
this.gsiIndexKey = indexKey;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/459168.html
標籤:爪哇 春天 亚马逊-dynamodb
