如何从List <object []>创建一个select元素?

时间:2017-03-02 14:21:03

标签: jsp spring-mvc

有一个DAO方法返回List:

@Transactional
public List<Object[]> list() {

    String sql = "select pnd_code, to_char(pnd_intitule) l from pnd order by l"; // pnd_intitule is a CLOB column

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);

    @SuppressWarnings("unchecked")
    List<Object[]> list = (List<Object[]>) query.list();

    return list;

}

在我的JSP中,我想从中创建一个select元素;这是我尝试过的(但它在运行时崩溃了):

<select id="pnd" style="width:500px;">
    <option value=""> -- S&eacute;lectionner -- </option>
    <c:forEach items="${pnds}" var="pnd">
        <option value="${pnd.pnd_code}">${pnd.l}</option>
    </c:forEach>
</select>

那么如何在这种情况下创建select元素?

1 个答案:

答案 0 :(得分:1)

帮自己一个忙,创建一个封装数据的自定义类。

class MyCustomClass{ // change name
    private final String lecturer;
    private final String code:
    // initialize fields in constructor
    // add getters
}

DAO课程:

public List<MyCustomClass> list() {

    String sql = "select pnd_code, to_char(pnd_intitule) l from pnd order by l"; // pnd_intitule is a CLOB column

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);

    @SuppressWarnings("unchecked")
    return ((List<Object[]>) query.list())
         .stream()
         .map(oo -> new MyCustomClass(oo[0].toString(), oo[1].toString()))
         .collect(Collectors.toList());

}

Old-school Java 7版本:

public List<MyCustomClass> listWithoutLambdasAndStreams() {

    String sql = "select pnd_code, to_char(pnd_intitule) l from pnd order by l"; // pnd_intitule is a CLOB column

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);

    @SuppressWarnings("unchecked")
    List<Object[]> list = (List<Object[]>) query.list();
    List<MyCustomClass> youShouldReallyLearnAboutLambdasAndStreams =
        new  ArrayList<>(list.size());
    for(Object[] oo: list){
        youShouldReallyLearnAboutLambdasAndStreams.add(
            new MyCustomClass(oo[0].toString(), oo[1].toString()));
    };
    return youShouldReallyLearnAboutLambdasAndStreams;
}

JSP:

<select id="pnd" style="width:500px;">
    <option value=""> -- S&eacute;lectionner -- </option>
    <c:forEach items="${pnds}" var="pnd">
        <option value="${pnd.code}">${pnd.lecturer}</option>
    </c:forEach>
</select>