How to update an entire object using jdbcTemplate without specifying column names?
Asked Answered
B

3

6

I was looking at the reference here. We can do this -

String orderSql = "select * from order where id = ?"; jdbcTemplate.query(orderSql, new BeanPropertyRowMapper<>(Order.class), orderId);

This reads from the database and can directly deserialise into the Order object. This is well and good.

What I want to do is -

String updateSql = "update order ? where id = ?"; jdbcTemplate.save(updateSql, new BeanPropertyRowMapper<>(Order.class), order, orderId);

Is there a way of doing this?

Ballentine answered 16/7, 2018 at 13:19 Comment(6)
Why don't you write a method to build the query first based on the column information and return that query to use in the jdbcTemplate.update(...) method.Amin
That is a way but wouldn't it be more convenient to just pass in an object and let it decide which columns have changed and update the corresponding?Ballentine
you are not passing object, and if you wish so i recommend to use hibernate it knows the state of object.Amin
That is called JPA... Spring has now way of knowing what columns to persist. The row mapper is a best effort and only works if the names match exactly. If you want to do updates like that, use JPA instead.Zampino
I've used JPA before which works this way. For some reason we decided to use raw queries with jdbctemplate. Hence the question!Ballentine
With that decision also comes the fact that you will have to manually write your insert/update queries.Zampino
S
1

No, it's not possible. JdbcTemplate comes with the ability to map an object using query as you've said without having to define columns/attributes, but there is no equivalent usage for update. You will have to pass in your SQL and the relevant parameters. As someone has mentioned if you really want to do this you could consider using hibernate.

Sabadilla answered 16/7, 2018 at 13:40 Comment(0)
P
1

Use this query for update :-

String updateSql = "update <table_name> set order= ? where id = ?";

jdbcTemplate.update(updateSql, new Object[]{order, orderId});

It will return affected row update count.

Photoactive answered 17/7, 2018 at 6:30 Comment(0)
I
0

No ! You can only do this !

jdbcTemplate.update("update ordertable set order = ? where id = ?", order, orderId);
Ides answered 16/7, 2018 at 13:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.