【Java】S2Dao SQLアノテーション
S2Daoでデータベースアクセス。DoltengプラグインをインストールするときH2データベースがインストールされ、デフォルトでテーブルも作成される。そのテーブルへのアクセスを試してみる。
search.html
ID:<input type="text" id="empId" /><br /> <input type="button" id="doSearcEmpId" value="検索"/><br /> <br /> ID数検索:<input type="button" id="doSearchCount" value="計算" />
SearchPage.java
package com.xxx.web.search; public class SearchPage { public Long empId; public Integer empCount; public Long getEmpId() { return empId; } public void setEmpId(Long empId) { this.empId = empId; } public Class<?> doSearcEmpId() { return ResultListPage.class; } public Class<?> doSearchCount(){ return ResultCountPage.class; } public Class<?> initialize() { return null; } public Class<?> prerender() { return null; } }
自動生成してくれるDaoインターフェースをいじる。レコード数をカウントするメソッド(count())を追加。SQLアノテーション(@Sql〜)で、SQLをそのまま書けばいいとのこと。
EmpDao.java
package com.xxx.dao; import org.seasar.dao.annotation.tiger.Arguments; import org.seasar.dao.annotation.tiger.S2Dao; import org.seasar.dao.annotation.tiger.Sql; import com.xxx.entity.Emp; @S2Dao(bean=Emp.class) public interface EmpDao { public Emp[] selectAll(); @Arguments("ID") public Emp selectById(Long id); public int insert(Emp emp); public int update(Emp emp); public int delete(Emp emp); @Sql("SELECT count(*) FROM emp") public int count(Emp emp); }
んで、結果表示のページ。IDで検索した結果を表示するhtml。
ResultList.html
ID:<span id="empId" /><br /> <table border="1" class="tablebg"> <thead> <tr> <th>社員番号</th> <th>社員名</th> <th>上司ID</th> <th>入社日</th> <th>給料</th> <th>部門ID</th> </tr> </thead> <tbody id="empItems"> <tr id="empRow" class="row_even"> <td class="right"><span id="empNo">empNo</span></td> <td><span id="empName">empName</span></td> <td class="right"><span id="mgrId">mgrId</span></td> <td><span id="hiredate">hiredate</span></td> <td class="right"><span id="sal">sal</span></td> <td class="right"><span id="deptId">deptId</span></td> </tr> </tbody> </table>
IDで検索して、その結果を出力する。
ResultListPage.java
package com.xxx.web.search; import com.xxx.entity.Emp; import com.xxx.web.emp.AbstractEmpPage; public class ResultListPage extends AbstractEmpPage { //public Emp[] empItems; public Emp empItems; public Long empId; public Class<?> prerender() { //empItems = empDao.selectAll(); //long empId = 1; empItems = empDao.selectById(empId); empDxo.convert(empItems, this); return null; } }
今度はカウント数を。ResultCount.html
社員数:<span id="empCount" >count</span>
ResultCountPage.java
package com.xxx.web.search; import com.xxx.web.emp.AbstractEmpPage; import com.xxx.entity.Emp; public class ResultCountPage extends AbstractEmpPage { public Integer empCount; public Emp emp; public Integer getEmpCount() { return empCount; } public void setEmpCount(Integer empCount) { this.empCount = empCount; } public Class<?> initialize() { return null; } public Class<?> prerender() { empCount = empDao.count(emp); empDxo.convert(empCount, this); return null; } }
一応、初歩的なとこは、なんとか。次からはCRUDを。