1.准备条件
1.1 创建用户图片表
CREATE TABLE `micro_user_img` ( `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT '用户id', `uid` int unsigned DEFAULT NULL COMMENT '用户id', `uri` varchar(50) COLLATE utf8mb4_bin NOT NULL DEFAULT '' COMMENT '图片uri', `create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间', `is_delete` tinyint unsigned DEFAULT '0' COMMENT '1:删除 0:未删除', PRIMARY KEY (`id`) USING BTREE, KEY `uid` (`uid`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用户图片表';
|
1.2 生成Dao、实体类、Mapper文件
通过MyBatis Generator
直接生成,关于如何生成,详情请看 SpringBoot学习(四):集成Mybatis代码生成器(MyBatis Generator)
2. 使用动态SQL
2.1 修改UserImgDao
修改: UserImgDao.java
package com.hui.javalearn.dao;
import com.hui.javalearn.model.UserImgModel; import java.util.List;
public interface UserImgDao {
int deleteByPrimaryKey(Integer id);
int insert(UserImgModel record);
int insertSelective(UserImgModel record);
int updateByPrimaryKey(UserImgModel record);
int batchInsert(List<UserImgModel> userImgModels);
}
|
2.2 添加对接的Xml
修改: UserImgDao.xml
<insert id="batchInsert" parameterType="java.util.List"> INSERT into micro_user_img(`uid`,`uri`,`create_time`) VALUES <foreach collection="list" item="item" index="index" separator=","> (#{item.uid,jdbcType=INTEGER},#{item.uri,jdbcType=VARCHAR},#{item.createTime,jdbcType=TIMESTAMP}) </foreach> </insert>
|
2.3 使用
package com.hui.javalearn;
import cn.hutool.core.date.DateUtil; import com.hui.javalearn.dao.UserImgDao; import com.hui.javalearn.model.UserImgModel; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date;
@SpringBootTest public class TestUseMybatis {
@Resource private UserImgDao userImgDao;
@Test void testBatchInsertByXml() throws ParseException { ArrayList<UserImgModel> userImgModels = new ArrayList<>(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat.format(new Date()); Date nowDate = simpleDateFormat.parse(format); DateUtil.today(); for (int i = 0; i < 20; i++) { UserImgModel userImgModel = new UserImgModel(); userImgModel.setUid(100010); userImgModel.setUri("/img/uir/"+i); userImgModel.setCreateTime(nowDate); userImgModels.add(userImgModel); } int res = userImgDao.batchInsert(userImgModels); System.out.println("ok" + res);
} }
|
注意: 在Mybatis
使用Mysql
,sql
默认有长度限制,为10486576(1M),该方式若超过,会抛出异常。