项目基于前博客。
1.单条插入
在接口UserDao文件下添加接口:
void addUser(UserModel userModel);
在UserController下添加方法:
@RequestMapping(value = "/addUser", method = RequestMethod.GET)
public void addUser(@RequestParam("userName") String userName,
@RequestParam(value = "userAge",defaultValue = "0") Integer userAge){
UserModel user = new UserModel();
user.setUserAge(userAge);
user.setUserName(userName);
userDao.addUser(user);
}
在mapper的UserDAO.xml添加数据库sql:
<insert id="addUser" parameterType="com.lml.helloworld3.pojo.UserModel">
INSERT INTO user_first (user_name, user_age) value (#{userName}, #{userAge})
</insert>
测试成功!
2.批量插入
在接口UserDao文件下添加接口:
void addUsers(List<UserModel> users);
在UserController下添加方法:
@RequestMapping(value = "/addUsers", method = RequestMethod.GET)
public void addUsers(){
List<UserModel> list = new ArrayList<>();
UserModel user1 = new UserModel();
user1.setUserAge(1);
user1.setUserName("u1");
list.add(user1);
UserModel user2 = new UserModel();
user2.setUserAge(2);
user2.setUserName("u2");
list.add(user2);
userDao.addUsers(list);
}
在mapper的UserDAO.xml添加数据库sql:
<insert id="addUsers" parameterType="java.util.List">
insert into user_first (user_name, user_age) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.userName,jdbcType=VARCHAR},
#{item.userAge,jdbcType=BIGINT})
</foreach>
</insert>
测试成功!
网友评论