Nit*_*tal 2 java jdbc apache-commons-dbutils
我想使用Apache DBUtils库从数据库填充POJO(State.java)。但是,由于Bean属性的名称与DB列名称不完全匹配,因此某些属性未填写。
现在,我通过谷歌搜索对此进行了一些研究,发现可以通过以下方法实现:
谁能提供一个很好的例子说明如何使用BeanProcessor将列名映射到属性?调整示例为我提供的效果会更好。
数据库表
CREATE TABLE public.states (
state_id INTEGER DEFAULT nextval('states_seq'::regclass) NOT NULL,
state_cd VARCHAR(2) NOT NULL,
name VARCHAR(100) NOT NULL,
tax_pct NUMERIC(10,2) DEFAULT 0.00 NOT NULL,
active CHAR(1) DEFAULT 'Y'::bpchar NOT NULL,
)
Run Code Online (Sandbox Code Playgroud)
State.java
public class State implements Serializable {
private int stateId;
private String stateCode;
private String name;
private BigDecimal taxPct = new BigDecimal(0);
private Date expiryDate;
private String createdBy;
private Date createdOn;
private String active;
//getters and setters here
}
Run Code Online (Sandbox Code Playgroud)
Main.java
public class Main {
public static void main(String[] args) {
String url = "jdbc:postgresql://gsi-547576.gsiccorp.net:5432/istore-db";
String driver = "org.postgresql.Driver";
String user = "postgres";
String pwd = "postgres";
Connection conn = null;
List<State> states = null;
try {
DbUtils.loadDriver(driver);
conn = DriverManager.getConnection(url, user, pwd);
states = (List<State>) new QueryRunner().query(conn, "select * from states a where a.active='Y'", new BeanListHandler(State.class);
System.out.println("states:: " + states);
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Map<String,String> mapColumnsToProperties = new HashMap<>();
//mapping you database to entity here;
mapColumnsToProperties.put("database_column","entity_property");
BeanProcessor beanProcessor = new BeanProcessor(mapColumnsToProperties);
RowProcessor rowProcessor = new BasicRowProcessor( beanProcessor);
ResultSetHandler<List<Entity>> resultSetHandler = new BeanListHandler<Entity>(Entity.class,rowProcessor);
List<Entity> entityLists = queryRunner.query(findListSQL, resultSetHandler);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6253 次 |
| 最近记录: |