LabelValueBeanの使い方

LabelValueBeanの使い方

LabelValueBeanは、セレクトボックスなどで使えるキーと値を保持するクラスです。

org.apache.struts.utilクラスにありますがあまり知られていないです。

List<LabelValueBean> list = new ArrayList<LabelValueBean>();
list.add(new LabelValueBean("あいう","1");
list.add(new LabelValueBean("えお","2");
inForm.setSelectBoxList(list);

このlistをセレクトボックスにセットするだけです。

JSP側は以下のようにします。

<html:select property="selectBox">
  <heml:optionsCollection name="Bean名" property="selectBoxList" />
</html:select>

DBから取得した値をセレクトボックスにしたい場合は以下のようなコードになると思います。

List<LabelValueBean> selectBox = new ArrayList<LabelValueBean>();
List<entityクラス> entityList = DAO.selectMethod();
for(entityクラス list entityList){
  selectBox.add(new LabelValueBean(list.getId(),list.getValue());
}

MyBatisでコンボボックスにLabelValueBeanを使う方法

ORマッパーのMyBatisでList<LabelValueBean>を作成することができます。

org.apache.ibatis.session.SqlSession#selectListメソッドを使用して、戻り値をList<LabelValueBean>とすることができます。

Java記述例は以下のようなイメージです。

List<LabelValueBean> list = sess.selectList("a.xml");

a.xml内のresultTypeにLabelValueBeanを指定します。

<select id="sqlid001" resultType="org.apache.struts.util.LabelValueBean">
SELECT
LABEL as label,
VALUE as value
FROM SAMPLE_TBL
WHERE CODE = '00'
</select>

MyBatisの記述方法

コメント

タイトルとURLをコピーしました