Is it possible to use a instanced pojo to insert with a JDBC template?

时光怂恿深爱的人放手 提交于 2020-12-12 01:25:27

问题


Spring has the BeanPropertyRowMapper to pull from SQL on a select and map to a POJO object without having to make a custom row mapper. I'm hoping for the same but for an insert statement. But I'm unable to find an equivalent.

public boolean addRenewalQuote(Quote quote) {

    String sql = "INSERT INTO Customers (internal_order_number, b_email, s_email, b_firstname) VALUES (?, ?, ?, ?);";

    if(getTemplate().update(sql, quote) > 0) {
        return true;
    }else {
        return false;
    }
}

The quote string names match the columns in the DB already. The actual insert is quite large and I'm hoping there is a faster method than grabbing each quote getter individually and passing it to the update method.


回答1:


Kind of, but you will have to access the pojo's member variables like this:

Object[] args = new Object[] {quote.getOrderNumber(), quote.getBEmail(), quote.getSEmail(), quote.getFirstName()};
int[] types = new int[] {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
getTemplate().update(sql, args, types};

Don't forget to change the args array and types array accordingly.

Also, you can read more into the documentation here.



来源:https://stackoverflow.com/questions/24043241/is-it-possible-to-use-a-instanced-pojo-to-insert-with-a-jdbc-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!