Mybatis使用注解的方式CRUD包括批量插入更新

定义一个Mapper接口:

@Mapper
@Repository
public interface ConfigMapper {
}

查询注解@Select

@Select("select * from config where id=#{id}")
Config findById(Long id);

删除注解@Delete

@Delete("delete from config where id=#{id}")
@Options(useGeneratedKeys = true)
Long deleteById(Long id);

其中@Options注解常用属性:
- flushCache:刷新缓存策略,有DEFAULT,TRUE,FALSE三种值,默认DEFAULT表示刷新查询语句的缓存
- useCache:默认true,表示使用缓存
- fetchSize:查询时的获取数量
- useGeneratedKeys:默认false,是否返回插入的id
- keyProperty:实体类id属性
- keyColumn:实体类属性对应数据库的字段

插入注解@Insert

@Insert("insert into config(cron) values(#{cron})")
@Options(useGeneratedKeys = true)
Long save(Config config);

批量插入@InsertProvider

@InsertProvider(type = ConfigDaoProvider.class, method = "saveAll")
void saveAll(@Param("list") Collection<Config> configs);

ConfigDaoProvider.java:

  public String saveAll(Map map) {
        List configs = (List) map.get("list");
        StringBuilder sb = new StringBuilder();
        sb.append("insert into config");
        sb.append("(cron)");
        sb.append("values");
        MessageFormat mf = new MessageFormat("#'{'list[{0}].cron'}'");
        for (int i = 0; i < configs.size(); i++) {
            sb.append("(");
            sb.append(mf.format(new Object[]{i}));
            sb.append(")");

            if (i < configs.size() - 1) {
                sb.append(",");
            }
        }

        return sb.toString();
    }

更新注解@Update

@Update("update config set cron=#{cron} where id=#{id}")
void update(Config config);

批量更新@UpdateProvider

 @UpdateProvider(type = ConfigDaoProvider.class, method = "updateAll")
void updateAll(@Param("list") Collection<Config> configs);

updateAll方法:

 public String updateAll(Map map) {
        List configs = (List) map.get("list");
        StringBuilder sb = new StringBuilder();
        sb.append("update config ");
        sb.append("set cron=case id ");
        MessageFormat mfCron = new MessageFormat("#'{'list[{0}].cron'}'");
        for (int i = 0; i < configs.size(); i++) {
            sb.append("when ");
            sb.append(configs.get(i).getId());
            sb.append("then ");
            sb.append(mfCron.format(new Object[]{i}));
        }
        sb.append("end ");
        sb.append("where id in");
        sb.append("(");
        for (int i = 0; i < configs.size(); i++) {
            sb.append(configs.get(i).getId());
            if (i < configs.size() - 1) {
                sb.append(",");
            }
        }
        sb.append(")");
        return sb.toString();
    }

以上。。。

你可能感兴趣的:(Mybatis)