Mybatis批量更新
-
應用環境
Mybatis、Mysql -
實體類
public class ServiceGroup { private Integer id; private String services; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getServices() { return services; } public void setServices(String services) { this.services = services; } }
-
Mapper接口
public interface ServiceGroupMapper { public void updateServices(List<ServiceGroup> update); }
-
Mapper.xml文件中的update語句
<update id="updateServices" parameterType="com.zongze.domain.ServiceGroup"> update service_group <trim prefix="set" suffixOverrides=","> <trim prefix=" services = case" suffix="end,"> <foreach collection="list" index="index" item="item"> when id = #{item.id, jdbcType=INTEGER} then #{item.services, jdbcType=LONGVARCHAR} </foreach> </trim> </trim> when id in <foreach close=")" collection="list" item="item" open="(" separator=","> #{item.id, jdbcType=INTEGER} </foreach> </update>
-
控制檯輸出SQL語句
update service_group set services = CASE WHEN id=? THEN ? WHEN id=? THEN ? END WHERE id in (?,?)
-
Mysql語句
update service_group set services = CASE WHEN id=1 THEN '{"服務1,服務2"}' WHEN id=2 THEN '{"服務2,服務3"}' END WHERE id in (1,2);