3

Spring MVCのカスタムエディターを使用して、文字列値をドメインオブジェクトにマップしています。単純なケース:ユーザーオブジェクトは会社を参照します(User.company-> Company)。ユーザーフォームでデータバインダーを登録します。

protected void initBinder(WebDataBinder binder) throws Exception {
    binder.registerCustomEditor(Company.class, new CompanyEditor(appService));
}

エディタは次のように定義されます。

class CompanyEditor extends PropertyEditorSupport {

    private AppService appService;  

    public CompanyEditor(AppService appService) {
        this.appService = appService;
    }

    public void setAsText(String text) {
        Company company = appService.getCompany(text);
        setValue(company);
    }

    public String getAsText() {
        Company company = (Company) this.getValue();
        if (company != null)
            return company.getId();
        return null;
    }    
}

フォームでドロップダウンを使用する場合

<form:select path="company">
    <form:options items="${companies}" itemLabel="name" itemValue="id"/>
</form:select>

(会社が選択されているかどうかを確認するために)オプションごとにsetAsTextとgetAsTextを起動し、会社ごとにSQLクエリを実行するため、パフォーマンスに深刻な問題が発生します。

フォームをコミットして、会社のIDをCompany(永続化された)オブジェクトに変換する方法をアプリケーションに知らせるときに、setAsTextが使用されると思いました。ドロップダウンで起動する必要があるのはなぜですか。それを修正する方法はありますか?

4

1 に答える 1

2

フォームバッキングオブジェクトがセッション属性として保存されている場合(つまり、コントローラーに似たようなものがある場合)、メソッド@SessionAttributes("command")を変更してみることができますsetAsText(String text)

public void setAsText(String text) {
        Company currentCompany = (Company) this.getValue();
        if ((currentCompany != null) && (currentCompany.getId().equals(text)))
          return;

        Company company = appService.getCompany(text);
        setValue(company);
    }

しかし、Spring 3.1 @Cacheable 抽象化はまさにそのようなもののために導入されたものであり、好ましいと思います

ドキュメントの例を参照してください

@Cacheable("books")
public Book findBook(ISBN isbn) {...}

PSプロパティ エディタの代わりに、新しいコンバータ SPIの使用を検討してください。

一般に、ルックアップ エンティティ用のジェネリック コンバーターを実装することは可能です。そのため、特定の属性がある場合、id を使用してエンティティをテキストから自動的に変換します。たとえば、私のプロジェクトの 1 つで、すべての@EntityタイプがグローバルなConditionalGenericConverter実装であるため、バインド中にカスタム プロパティ エディターを登録したり、注釈付きの主キー@Entityを持つ単純なクラスである型の特定のコンバーターを実装したりしません。@Id

@RequestParamまた、テキスト オブジェクト ID がアノテーション付きのコントローラー メソッド引数として指定されたときに、Spring がテキスト オブジェクト ID を実際のエンティティーに自動的に変換すると、非常に便利です。

于 2012-08-10T09:59:38.963 に答える