現在のコードは
私はちょうどあなたがあなたのhtmlに基づいて、次のクラスを使用していることを仮定しているので、出発点としてそれらを取ることができます。
/* This may be called City in your code */
public class Item {
private Long id;
private String description;
// getter/setter/constructor here...
}
public class ContactForm {
private Long cityId;
// getter/setter/constructor here...
}
ここで問題を解決するにはどうすればよいですか?
Springでは、コンバーターを特定のクラスに追加する簡単な方法が提供されているため、たとえばStringをYearオブジェクトに変換することについて心配する必要はありません。 Itemクラスのような他のクラスでも同じテクニックを使用できます。それに見てみましょう:それはタイプItem
と実際のJavaフィールドに(フォームの入力から)文字列を変換しようとするたび
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class StringToItemConverter implements Converter<String, Item> {
@Override
public Item convert(String source) {
if(source != null) {
try {
Long id = Long.parseLong(source);
return /* insert your logic for getting an item by it's id here */;
} catch(Exception e) {
return null;
}
}
return null;
}
}
上記のコードは自動的に春によって実行されます。したがって、ContactFormクラスを少し変更すると、Springは自動的に指定されたidのItemオブジェクトを設定します。
public class ContactForm {
/* Note that cityId now has all the information you need (id and description) You should however consider renaming it to city. Don't forget to change the th:field name too! ;) */
private Item cityId;
// getter/setter/constructor here...
}
あなたはSpringリポジトリで作業していますか?
データベースにアイテムを格納する場合、CrudRepositoryを使用する可能性が最も高いでしょう。その場合、コードは次のようになります。 Repositoryクラスの名前がItemRepositoryであるとしましょう。
@Component
public class StringToItemConverter implements Converter<String, Item> {
private ItemRepository itemRepository;
@Autowired
public void setItemRepository (ItemRepository itemRepository) {
this.itemRepository = itemRepository;
}
@Override
public Item convert(String source) {
if(source != null) {
try {
Long id = Long.parseLong(source);
return itemRepository.findOne(id);
} catch(Exception e) {
return null;
}
}
return null;
}
}
上記のコードは、データベース内のIDをルックアップすることにより実際のItem
-object形からの文字列を変換しようとするだろう。したがって、私たちはItem
を取得するか、何かがうまくいかない場合はnullを返します(たとえば、そのIDの項目がないか、文字列を長く解析できない場合など)。
詳細な回答ありがとうございます。アイテムオブジェクトを取得するために、私はデータベースにヒットする必要がありますか?私はth = value = "$ {item}"のようなものを期待していました。私は角度のあるJS ng-model = "item"のようなものを望んでいました.Content Postを投稿すると、SpringはConcatFormとItemオブジェクトを@RequestBodyから自動的に構築します。しかし、私たちがサーバー側のテンプレートを使用する場合、これが限界であると理解しています – Mukun
データベースからそれを探す必要はありません。どのように正常にあなたのコードのIDでアイテムを検索するだろうか? –
私はitemRepository.findOne(id)を使用します。オブジェクトがキャッシュにない場合、それはDBの権利を打つでしょうか? – Mukun