--When you want to insert List data, it is useless to insert one by one, so you want to insert all the data at once. --Customized Mapper automatically generated by MyBatisGenerator
--Be careful as it will be overwritten and disappear if you generate it again. --It seems that the method is different when the ID is AUTO INCREMENT.
There are two things to do.
For example, suppose you have a table like this (MySQL).
user_friend.sql
CREATE TABLE user_friend (
user_id int(10) NOT NULL,
friend_id int(10) NOT NULL
friend_name varchar(30) NOT NULL,
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
PRIMARY KEY (user_id, friend_id)
);
--Add a method of insertBulk
--Pass the List of the data you want to insert as an argument
--It is optional to name it with @Param
UserFriendMapper.java
int insertBulk(@Param("friendList")List<UserFriend> friendList);
--Add ʻinsert id =" insertBulk " to ʻUserFriendMapper.xml
--Specify in parameterType =" java.util.List "
--Specify collection =" list "
if you did not specify @ Param
in Mapper
UserFriendMapper.xml
<!--Add this-->
<insert id="insertBulk" parameterType="java.util.List">
insert into user_friend
(user_id, friend_id, friend_name, created_at, updated_at)
values
<foreach collection="friendList" item="fr" separator=",">
(
#{fr.userId,jdbcType=INTEGER}, #{fr.friendId,jdbcType=INTEGER},
#{fr.friendName,jdbcType=VARCHAR}, #{fr.createdAt,jdbcType=TIMESTAMP},
#{fr.updatedAt,jdbcType=TIMESTAMP}
)
</foreach>
</insert>
Just call the method you added to the Mapper class.
FriendService.java
@Service
public class FriendService {
@Autowired
private UserFriendMapper userFriendMapper;
/**
* @number of return int inserts
*/
public int insertFriends(int userId, List<UserFriend> saveFriends) {
return userFriendMapper.insertBulk(saveFriends);
}
}
-Database access (MyBatis3 edition) Entity batch registration
Recommended Posts