共计 2048 个字符,预计需要花费 6 分钟才能阅读完成。
一、mybatis 插入一条数据
1. UserMapper.java 接口中插入函数如下:
/*
* 新增用户 ----- 使用 useGeneratedKeys 方式
* 测试主键自增的值 这里 主键自增的值不作为参数传递 直接由数据库那边赋值
* */
int insert4(SysUser sysUser);
2. UserMapper.xml 中 insert4 函数如下:
<insert id="insert4" useGeneratedKeys="true" keyProperty="id">
insert into sys_user (
user_name,user_password,
<if test="userEmail != null and userEmail !=''">
user_email,
</if>
user_info,head_img,create_time)
values (#{userName}, #{userPassword},
<if test="userEmail != null and userEmail !=''">
#{userMail},
</if>
#{userInfo},#{headImg, jdbcType = BLOB},
#{createTime, jdbcType= TIMESTAMP}
);
</insert>
3. 测试函数如下:
@Test
public void testInsert4(){SqlSession sqlSession = getSqlSession();
try{UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 创建一个 user 对象
SysUser user = new SysUser();
user.setUserName("test1");
user.setUserPassword("123456");
user.setUserEmail("test@mybatis.tk");
user.setUserInfo("test info");
user.setHeadImg(new byte[]{1,2,3});
user.setCreateTime(new Date());
int result = userMapper.insert3(user);
Assert.assertEquals(1,result);
Assert.assertNotNull(user.getId());
}finally {sqlSession.commit();
sqlSession.close();}
}
4. 运行结果如下:
二、mybatis 批量插入数据
1. 接口如下:
/*
* 批量插入用户信息
* */
int insertList(List userList);
2. xml 文件中:
<insert id="insertList">
insert into sys_user(user_name,user_password,
user_email,user_info,head_img,create_time)
values
<foreach collection="list" item="user" separator=",">
#{user.userName},#{user.userPassword},
#{user.userEmail},#{user.userInfo},
#{user.headImg ,jdbcType = BLOB},
#{user.createTime, jdbcType = TIMESTAMP}
</foreach>
</insert>
注:foreach 标签
collection:值为要迭代循环的属性名。
item:变量名,值为从法代对象中取出的每一个值。
index:索引的属性名,在集合数组情况下值为当前索引值 当选代循环的对象是 Map 类型时,这个值为 Map key(键值)。
3. 测试函数如下:
@Test
public void testInsertList(){SqlSession sqlSession = getSqlSession();
try {UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List userList = new ArrayList ();
for(int i=0 ; i<2 ; i++){SysUser sysUser = new SysUser();
sysUser.setUserName("test_" + i);
sysUser.setUserPassword("123456");
sysUser.setUserEmail("wct@qq.com");
}
int result = userMapper.insertList(userList);
Assert.assertEquals(2,result);
}finally {sqlSession.close();
}
}
正文完
星哥说事-微信公众号
![post-qrcode](https://www.xgss.net/wp-content/uploads/2023/07/二维码-微信公众号256x256.jpg)