QueryRunner run =new QueryRunner(dataSource); // Use the BeanHandler implementation to convert the first // ResultSet row into a Person JavaBean. ResultSetHandler<Person> h =new BeanHandler<Person>(Person.class); // Execute the SQL statement with one replacement parameter and // return the results in a new Person object generated by the BeanHandler. Person p = run.query( "SELECT * FROM Person WHERE name=?", h, "John Doe");
q里有个地方有约束,是要求CZ中的JavaBeancPerson中的字段定义要和数据库的字段定义一致。Java的命名习惯一般是骆峰写法Q例如userIdQ那么数据库中就必须定义为userIdQ而问题在于:有时候我们需要数据库中字D늚定义格式与JavaBean的命名不一P比如数据库定义ؓQuser_idQ而JavaBean则定义ؓuserId
看源代码可能有点Ҏ_在官方的example面的最下面果然有一D关于自定义BeanProcessor的指引。摘录出来: BasicRowProcessor uses a BeanProcessor to convert ResultSet columns into JavaBean properties. You can subclass and override processing steps to handle datatype mapping specific to your application. The provided implementation delegates datatype conversion to the JDBC driver.
BeanProcessor maps columns to bean properties as documented in the BeanProcessor.toBean() javadoc. Column names must match the bean's property names case insensitively. For example, the firstname column would be stored in the bean by calling its setFirstName() method. However, many database column names include characters that either can't be used or are not typically used in Java method names. You can do one of the following to map these columns to bean properties:
1. Alias the column names in the SQL so they match the Java names: select social_sec# as socialSecurityNumber from person
2. Subclass BeanProcessor and override the mapColumnsToProperties() method to strip out the offending characters.
大概意思就是提供二U方式:一U就是最直接的,用as关键字把colName重命名,另一U方式就是承BeanProcessorc,重写mapColumnsToProperties()Ҏ?br />
那当然是W二U方式更加具有代表性。尝试了一下。代码如下: