在 MyBatis 中,要實(shí)現(xiàn) BaseDao 的批量操作,你需要遵循以下步驟:
public interface BaseDao<T> {
int insert(T entity);
int update(T entity);
int delete(int id);
T getById(int id);
List<T> findAll();
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.BaseDao">
<!-- 這里的 ${tableName} 和 ${columnList} 需要在實(shí)際的子類 Mapper XML 文件中進(jìn)行動(dòng)態(tài)替換 -->
<insert id="insertBatch" parameterType="list">
INSERT INTO ${tableName} (${columnList})
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.id}, #{item.name}, ...)
</foreach>
</insert>
</mapper>
public interface UserDao extends BaseDao<User> {
int insertBatch(List<User> users);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.dao.UserDao">
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id property="id" column="id" />
<result property="name" column="name" />
<!-- 其他屬性映射 -->
</resultMap>
<include resource="com/example/dao/BaseDao.xml"/>
<insert id="insertBatch" parameterType="list">
INSERT INTO user (id, name, ...)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.id}, #{item.name}, ...)
</foreach>
</insert>
</mapper>
注意:這里的示例代碼僅供參考,實(shí)際應(yīng)用中需要根據(jù)你的項(xiàng)目結(jié)構(gòu)和需求進(jìn)行調(diào)整。同時(shí),批量操作可能會(huì)導(dǎo)致性能問題,請(qǐng)確保在合適的場(chǎng)景下使用。