JSF 2.0 JDBC統合の例
ここでは、JDBCを使用してJSF 2.0をデータベースと統合する方法を説明します。この例では、MySQLデータベースとTomcat Webコンテナを使用しています。
この例のディレクトリ構造

1.テーブル構造
”
customer
“テーブルを作成し、5つのダミーレコードを挿入します。その後、JSF `h:dataTable`を介して表示します。
SQLコマンド
DROP TABLE IF EXISTS `mkyongdb`.`customer`; CREATE TABLE `mkyongdb`.`customer` ( `CUSTOMER__ID` bigint(20) UNSIGNED NOT NULL AUTO__INCREMENT, `NAME` varchar(45) NOT NULL, `ADDRESS` varchar(255) NOT NULL, `CREATED__DATE` datetime NOT NULL, PRIMARY KEY (`CUSTOMER__ID`) ) ENGINE=InnoDB AUTO__INCREMENT=17 DEFAULT CHARSET=utf8; insert into mkyongdb.customer(customer__id, name, address, created__date) values(1, 'mkyong1', 'address1', now()); insert into mkyongdb.customer(customer__id, name, address, created__date) values(2, 'mkyong2', 'address2', now()); insert into mkyongdb.customer(customer__id, name, address, created__date) values(3, 'mkyong3', 'address3', now()); insert into mkyongdb.customer(customer__id, name, address, created__date) values(4, 'mkyong4', 'address4', now()); insert into mkyongdb.customer(customer__id, name, address, created__date) values(5, 'mkyong5', 'address5', now());
2. MySQLデータソース
「
jdbc/mkyongdb
」という名前のMySQLデータソースを設定するには、この記事の
Tomcat 6でMySQL DataSourceを設定する方法
3.モデルクラス
テーブルレコードを格納する ”
Customer
“モデルクラスを作成します。
File:Customer.java
package com.mkyong.customer.model;
import java.util.Date;
public class Customer{
public long customerID;
public String name;
public String address;
public Date created__date;
//getter and setter methods
}
4. JDBCの例
JSF 2.0マネージドBeanで、@ Resourceを介してデータソース「
jdbc/mkyongdb
」を注入し、通常のJDBC APIを使用してデータベースからすべての顧客レコードを取り出し、リストに格納します。
ファイル:Customer Bean.java
package com.mkyong;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.mkyong.customer.model.Customer;
@ManagedBean(name="customer")
@SessionScoped
public class CustomerBean implements Serializable{
//resource injection
@Resource(name="jdbc/mkyongdb")
private DataSource ds;
//if resource injection is not support, you still can get it manually.
/** public CustomerBean(){
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mkyongdb");
} catch (NamingException e) {
e.printStackTrace();
}
}** /
//connect to DB and get customer list
public List<Customer> getCustomerList() throws SQLException{
if(ds==null)
throw new SQLException("Can't get data source");
//get database connection
Connection con = ds.getConnection();
if(con==null)
throw new SQLException("Can't get database connection");
PreparedStatement ps
= con.prepareStatement(
"select customer__id, name, address, created__date from customer");
//get customer data from database
ResultSet result = ps.executeQuery();
List<Customer> list = new ArrayList<Customer>();
while(result.next()){
Customer cust = new Customer();
cust.setCustomerID(result.getLong("customer__id"));
cust.setName(result.getString("name"));
cust.setAddress(result.getString("address"));
cust.setCreated__date(result.getDate("created__date"));
//store all data into a List
list.add(cust);
}
return list;
}
}
5. JSF Page dataTable
JSF 2.0のxhtmlページで、 `h:dataTable`を使用してすべての顧客レコードを表レイアウト形式で表示します。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:head>
<h:outputStylesheet library="css" name="table-style.css" />
</h:head>
<h:body>
<h1>JSF 2.0 + JDBC Example</h1>
<h:dataTable value="#{customer.getCustomerList()}" var="c"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
>
<h:column>
<f:facet name="header">
Customer ID
</f:facet>
#{c.customerID}
</h:column>
<h:column>
<f:facet name="header">
Name
</f:facet>
#{c.name}
</h:column>
<h:column>
<f:facet name="header">
Address
</f:facet>
#{c.address}
</h:column>
<h:column>
<f:facet name="header">
Created Date
</f:facet>
#{c.created__date}
</h:column>
</h:dataTable>
</h:body>
</html>
6.デモ
それを実行し、出力を参照してください

ソースコードをダウンロードする
ダウンロード – リンク://wp-content/uploads/2010/12/JSF-2-JDBC-Integration-Example.zip[JSF-2-JDBC-Integration-Example.zip](12KB)
リファレンス
-
link://java/how-to-connect-to-mysql-with-jdbc-driver-java/[JDBC
Tomcat 6のデータソースの例]。リンク://tomcat/how-to-configure-mysql-datasource-in-tomcat-6/[Configurate
Tomcat 6のMySQLデータソース]。
JSF 2 dataTableの例
integration
jdbc
リンク://タグ/jsf2/[jsf2]