適切なマッピングを可能とする為、OJBでは、ConversionStrategyという
インタフェースをImplementしたクラスを定義することが可能です。
上で示した問題に対処する為、以下のArticleConversionStrategyクラスを
定義する事にします。
ArticleConversionStrategyクラスは、ojb.broker.ConversionStrategyインターフェースを
実装しており、2つのメソッドが用意されているものとします:javaToSql 及び sqlToJava.
sqlToJavaメソッドは、JDBCのResultSetからオブジェクトの属性を読み込む際に、OJBのブローカ内でコールバックをします。ConversionStrategyは、クラス毎に定義されます。
Thus we have to implement
behaviour for all persistent attributes of the class. In this case I
just implement special behaviour for the attribute isSelloutArticle,
for all other attributes the input value is returned unmodified.
But if this method is called for the attribute isSelloutArticle it
maps the incoming (from the JDBC resultset) Integer values to the
corresponding Boolean values. The mapping from Boolean values to the
attributes primitive type boolean is done by the OJB broker
internally by means of Java reflection.
javaToSqlメソッドは、新規あるいは更新されたオブジェクトの、SQL上の挿入(insert)・更新(update)といった逆変換を記述するのに使われます。
 |  |  |
 |
public class ArticleConversionStrategy implements ojb.broker.ConversionStrategy
{
private Integer i_true = new Integer(1);
private Integer i_false = new Integer(0);
private Boolean b_true = new Boolean(true);
private Boolean b_false = new Boolean(false);
public Object javaToSql(Object source, FieldDescriptor fld)
{
if (fld.getPersistentField().getName().equals("isSelloutArticle"))
{
if (source.equals(b_true)) return i_true;
else return i_false;
}
else return source;
}
public Object sqlToJava(Object source, FieldDescriptor fld)
{
if (fld.getPersistentField().getName().equals("isSelloutArticle"))
{
if (source.equals(i_true)) return b_true;
else return b_false;
}
else return source;
}
}
|  |
 |  |  |
あと一つだけ、まだやらなければならない事が残っています:
ConversionStrategyをArticleクラスが使用する、ということをOJBに伝えなければなりません。XMLレポジトリでこの作業ができます。
ClassDescriptorにて、Strategyクラスの完全修飾名で宣言する<conversionStrategy>要素を規定することが出来ます。
 |  |  |
 |
<!-- Definitions for test.ojb.broker.Article -->
<ClassDescriptor id="1">
<class.name>test.ojb.broker.Article</class.name>
<class.proxy>test.ojb.broker.ArticleProxy</class.proxy>
<class.extent>test.ojb.broker.BookArticle</class.extent>
<class.extent>test.ojb.broker.CdArticle</class.extent>
<table.name>Artikel</table.name>
<conversionStrategy>test.ojb.broker.ArticleConversionStrategy</conversionStrategy>
...
<FieldDescriptor id="10">
<field.name>isSelloutArticle</field.name>
<column.name>Auslaufartikel</column.name>
<jdbc_type>INT</jdbc_type>
</FieldDescriptor>
...
</ClassDescriptor>
|  |
 |  |  |