-DbUtilsの癖?
FAQかもしれませんが、DbUtilsでハマリました。Beanではプリミティブのlong型、DBではBIGINTの型のプロパティ/フィールドがあって、DbUtilsのBeanHandlerで取るとき、このマップがうまくいきませんでした。以下テストケース。
create table LONGTEST ( JOBID bigint ); insert into LONGTEST values(999); commit;
package test; public class LongValueBean { private long jobID; public void setJobID(long jobID) { this.jobID = jobID; } public long getJobID() { return jobID; } }
package test; import javax.sql.DataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.seasar.extension.unit.S2TestCase; public class BasicRowProcessorTest extends S2TestCase { private DataSource dataSource; public BasicRowProcessorTest(String arg) { super(arg); } protected void setUp() throws Exception { super.setUp(); include("test/test.xml"); dataSource = (DataSource)getComponent(DataSource.class); } public void testLongValueCount() throws Exception { QueryRunner runner = new QueryRunner(dataSource); String sql1 = "select count(JOBID) from LONGTEST where JOBID=999"; Integer count = (Integer)runner.query(sql1, new ScalarHandler()); assertTrue(count.intValue() == 1); } private LongValueBean getBean() throws Exception { QueryRunner runner = new QueryRunner(dataSource); String sql2 = "select JOBID from LONGTEST where JOBID=999"; return (LongValueBean)runner.query(sql2, new BeanHandler(LongValueBean.class)); } public void testLongValueBean() throws Exception { LongValueBean bean = getBean(); assertNotNull(bean); } public void testLongValueProperty() throws Exception { LongValueBean bean = getBean(); long property = bean.getJobID(); System.out.println(property); assertTrue(property == 999L); } }
アサートが出るのは、一番最後のtestLongValueProperty()だけ。例外もでません。Beanのプロパティ値は0です。型を解決できなかった場合の例外がでなきゃいけないですね。カラム名=プロパティ名はOKなんだから。ちなみに、BeanのプロパティをintにすればOK。しかし、これでは予定する値が入らないのです。LongもBigIntegerもダメ。BIGINTのカラムに対応するプロパティ型はなんでしょうか?
とりあえずの解決策は、Handler自作です。
package test; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.dbutils.ResultSetHandler; import test.LongValueBean; public class LongValueBeanHandler implements ResultSetHandler { private BasicRowProcessor processor = BasicRowProcessor.instance(); public Object handle(ResultSet rs) throws SQLException { if(rs.next()) { LongValueBean bean = (LongValueBean)processor.toBean(rs, LongValueBean.class); // for DbUtils bug(?). bean.setJobID(rs.getLong("JOBID")); return job; } else { return null; } } }
まいった。まいった。