ejbLoadメソッドおよびejbStoreメソッドは、インスタンスの内容をデータベースと同期させるとき(例えば、ビジネスメソッドを呼び出す前やトランザクションをコミットする前)に、コンテナから呼び出されます。
記述する処理の概要
ejbLoadメソッドには、以下の処理を記述します。
該当するインスタンスのプライマリキーのレコードをデータベースから検索(SELECT)する処理
検索した結果を永続化フィールドに設定する処理
ejbStoreメソッドには、以下の処理を記述します。
永続化フィールドのデータを使用して、データベースのレコードを更新(UPDATE)する処理永続化フィールドが初期化された状態(create時)や、更新されていない場合は、更新する処理(UPDATE)を実行しないようにすることで性能向上が図れます。
ejbLoadメソッドおよびejbStoreメソッドの規約
ejbLoadメソッドおよびejbStoreメソッドは以下の規約を満たしていなければなりません。
メソッドはpublicとして定義されていなければなりません。
返却値はvoidでなければなりません。
throws句には以下の例外を定義できます。
任意のEJBアプリケーション固有の例外
javax.ejb.EJBException
javax.ejb.NoSuchEntityException
記述例
public void ejbLoad() throws javax.ejb.EJBException,javax.ejb.NoSuchEntityException
{
Connection connection = null;
PreparedStatement psSelect = null;
ResultSet rs = null;
SampleBeanPrimaryKey pk = null;
int rows = 0;
try
{
// レコードの検索
connection = dataSource.getConnection();
psSelect = connection.prepareStatement("SELECT ID,NAME,DESC FROM SAMPLESCM.SAMPLETBL WHERE ID = ?");
pk = (SampleBeanPrimaryKey)context.getPrimaryKey();
psSelect.setObject(1,pk.code);
rs = psSelect.executeQuery();
while(rs.next())
{
rows++;
// 検索結果を永続化フィールドに設定
code = new Integer(rs.getInt(1));
name = rs.getString(2);
desc = rs.getString(3);
}
}
catch(SQLException e)
{
throw new EJBException(e.getMessage());
}
finally
{
try
{
if (rs != null)
rs.close();
if (psSelect != null)
psSelect.close();
if (connection != null)
connection.close();
}
catch(Exception e) {}
}
if (rows == 0)
{
throw new NoSuchEntityException("No Record Found");
}
else if (rows > 1)
{
throw new EJBException("Many Records Found");
}
}
public void ejbStore() throws javax.ejb.EJBException,javax.ejb.NoSuchEntityException
{
Connection connection = null;
PreparedStatement psUpdate = null;
SampleBeanPrimaryKey pk = null;
int rows = 0;
try
{
// レコードの更新
connection = dataSource.getConnection();
psUpdate = connection.prepareStatement("UPDATE SAMPLESCM.SAMPLETBL SET NAME = ?,DESC = ? WHERE ID = ?");
pk = (SampleBeanPrimaryKey)context.getPrimaryKey();
psUpdate.setString(1,name);
psUpdate.setString(2,desc);
psUpdate.setObject(3,pk.code);
rows = psUpdate.executeUpdate();
}
catch(SQLException e)
{
throw new EJBException(e.getMessage());
}
finally
{
try
{
if (psUpdate != null)
psUpdate.close();
if (connection != null)
connection.close();
}
catch(Exception e) {}
}
if (rows != 1)
throw new EJBException("ejbStore failed");
}