最近在利用Springboot+Mybatis进行开发时,遇到批量操作的开发,目前Mybatis的批量操作通过mapper.xml文件实现的比较多,个人觉的通过注解的方式实现会更方便一些,于是研究了通过注解的方式来实现批量操作的方法,下面用批量更新作为例子。该例子的前提是项目已经整合了Springboot和Mybatis,可以进行正常的开发,只是对Dao层的改造,下面也只给出Dao层和Mapper文件的内容。
该例子总体思路还是利用了字符串拼接的方式,但在实现上利用了Mybatis的注解。在整体开发思路上和形式上和利用Mapper.xml文件没有什么区别,总体上符合Mybatis的开发规范。下面是相关源码:
实体类:
package com.study.entity;
public class UserDo {
private String userId;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
持久层:
package com.study.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.UpdateProvider;
import org.springframework.stereotype.Repository;
import com.study.dao.mapper.UserMapper;
import com.study.entity.UserDo;
@Mapper
@Repository
public interface UserDao {
@UpdateProvider(type = UserMapper.class, method = "updateBatchUser")
public int updateBatchUser(@Param("userDos") List<UserDo> userDos, @Param("otherConditon") String otherConditon);
}
Mapper文件(是java文件)
package com.study.dao.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.jdbc.SQL;
import com.study.entity.UserDo;
public class UserMapper {
String tableName = "user";
public String updateBatchUser(@Param("userDos") List<UserDo> userDos, @Param("otherConditon") String otherConditon) {
StringBuilder allSql = new StringBuilder();
for (int i = 0; i < userDos.size(); i++) {
SQL sql = new SQL();
sql.UPDATE(tableName);
sql.SET("user_name = " + userDos.get(i).getUserName());
sql.WHERE("user_id = '" + userDos.get(i).getUserId() + "'");
sql.WHERE("other_conditon = #{otherConditon}");
allSql.append(sql.toString());
allSql.append(";");
}
return allSql.toString();
}
}
总结:
在思路上就是利用了字符串的拼接,个人感觉这种方式更符合利用注解来开发,并可以解决大多数利用注解来实现批量操作的场景!
欢迎各位批评指正!
Only the fearless can be great. 只有勇者才能成功!