Reputation: 9559
Is is possible to have a MyBatis update where, instead of providing individual parameters, you can provide a bean containing the values to be updated?
Clarification:
Instead of this:
@Update("update widget set name=#{name}, manufacturer=#{manufacturer} where id=#{id}")
public void updateWidget(
@Param("id") int id,
@Param("name") String name,
@Param("manufacturer") String manufacturer);
Can you do something like this:
@Update("update widget set name=#{name}, manufacturer=#{manufacturer} where id=#{id}")
public void updateWidget(@Param("id") int id, Widget newValues);
Where newValues already contains the new values to be updated?
I have tried it, but I get the exception:
Exception in thread "main" org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'forename' not found. Available parameters are [id, 1, param1, param2]
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:368)
at com.sun.proxy.$Proxy8.update(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.update(SqlSessionTemplate.java:254)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:49)
Upvotes: 2
Views: 4673
Reputation: 747
You should specify second argument name and refer to it in your update statement.
@Update("update widget set name=#{newValues.name}, manufacturer=#{newValues.manufacturer} where id=#{id}")
public void updateWidget(@Param("id") int id, @Param("newValues") Widget newValues);
Upvotes: 5