2017-03-02 5 views
0

リストを返すDAOメソッドがあります:リストから選択要素を作成する方法<Object[]>?

私のJSPで
@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; 

} 

私はそれから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

自分の好きなことを行い、データをカプセル化するカスタムクラスを作成します。

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()); 

} 

古い学校の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> 
+0

エラーがある:ラムダ式は、ソースのみに許可されていますレベル1.8以上であれば、プロジェクトjreシステムライブラリを設定してもary to 1.8 – pheromix

+0

@pheromix次に、ソースレベル1.8に切り替えるか、またはlambdaを使用しないようにrefactor my code –

+0

ラムダ式について認識していないので、リファクタリングしてください。 – pheromix

関連する問題