I would like to populate a POJO (State.java) from DB using Apache DBUtils
library. However, since the names of the Bean properties do not match exactly with DB column names some of the properties are left unfilled.
Now, I did some research on this by googling and found that this can be achieved by:
- Column aliasing while writing an SQL query (which I do not prefer as I have multiple joins in some of larger tables and hence would require lot of aliasing)
- Using BeanProcessor (could not find a really good example anywhere)
Can anybody provide a good example on how to use BeanProcessor
to map column names to properties? Tweaking the example provided me would be even better.
DB Table
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,
)
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
}
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);
}
}
}