MyBatis Batch

Batch Update

1
2
3
4
5
6
7
8
9
10
interface PositionMapper {
fun insert(position: Position): Int
fun insertList(list: List<Position>): Int
fun updateList(list: List<Position>): Int
fun update(bean: Position): Int
fun find(id: Long): Position?
@Flush
fun flush(): List<BatchResult>
fun deleteAll()
}
1
2
3
4
5
6
7
8
9
10
 <update id="updateList" parameterType="it.unimi.dsi.fastutil.objects.ReferenceArrayList">
<foreach collection="list" item="item" index="index" open="" close="">
update tb_positions set
size=#{item.size},
cost=#{item.cost},
status=#{item.status},
update_time=#{item.updateTime}
where position_id=#{item.positionId};
</foreach>
</update>

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
fun getBatchCount(results: List<BatchResult>): Int {
if (results.isEmpty()) return 0

val batchResult = results[0]
if (batchResult.updateCounts.isEmpty()) return 0

return batchResult.updateCounts[0]
}

fun batchUpdate(positions: List<Position>): Boolean {
val session = MyBatisFactory.getSqlSession(type = ExecutorType.BATCH)
val mapper = session.getMapper(PositionMapper::class.java)
return try {
mapper.updateList(positions)
results = mapper.flush()
val updateRow = MyBatisUtil.getBatchCount(results)
if (updateRow > 0) updateRow = positions.size
session.commit()
updateRow == positions.size
} catch (e: RuntimeException) {
logger.error("batchUpdate(): occur error, error is", e)
session.rollback()
false
} finally {
session.close()
}
}

Batch Insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<insert id="insertList" parameterType="it.unimi.dsi.fastutil.objects.ReferenceArrayList">
INSERT INTO tb_positions(
size,
cost,
status,
create_time,
update_time
)
VALUES
<foreach collection="list" item="it" index="index" separator=",">
(
#{it.size},
#{it.cost},
#{it.status},
#{it.createTime},
#{it.updateTime}
)
</foreach>

</insert>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fun batchInsert(positions: List<Position>): Boolean {
val session = MyBatisFactory.getSqlSession(type = ExecutorType.BATCH)
val mapper = session.getMapper(PositionMapper::class.java)
return try {
mapper.insertList(positions)
results = mapper.flush()
val insertRow = MyBatisUtil.getBatchCount(results)
session.commit()
insertRow == positions.size
} catch (e: RuntimeException) {
logger.error("batchInsert(): occur error, error is", e)
session.rollback()
false
} finally {
session.close()
}
}

Reference