mysql8.0
目的:
批量操作:查询词不存在时插入数据,否则在原基础数量上增加。
表结构:
CREATE TABLE `frequencyWord` (
`id` int NOT NULL AUTO_INCREMENT,
`word` varchar(50) NOT NULL,
`time` int NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `word` (`word`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
批量语句:
INSERT INTO frequencyWord (word, `time`)
VALUES ('input', 2), ('scanner', 4)
ON DUPLICATE KEY UPDATE `time` = `time` + VALUES(`time`);
Mybatis xml文件编写:
<!-- 根据 name 更新 num,若不存在则插入新行 -->
<insert id="batchInsertOrUpdate" useGeneratedKeys="true" keyProperty="id">
INSERT INTO frequencyWord (word, `time`)
VALUES
<foreach collection="frequencyWordEntityList" item="entity" separator=",">
(#{entity.word}, #{entity.time})
</foreach>
ON DUPLICATE KEY UPDATE `time` = `time` + values(`time`)
</insert>
对应mapper层接口:
/**
* 批量插入更新词频,表中已有词频则加上次数
* @param frequencyWordEntityList 新增词频列表
*/
void batchInsertOrUpdate(List<FrequencyWordEntity> frequencyWordEntityList);
实体类:
@Data
@Accessors(chain = true)
@TableName("frequencyWord")
public class FrequencyWordEntity {
@TableId
private Integer id; // 主键
private String word; // 单词
private Integer time; // 数量
}
application.yaml配置mapper对应xml文件地址:(resources文件夹下mapper文件夹)
# mybatis-plus
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
参考自:
chatgpt
还不是合格的gpt工程师,弄这个花了不少时间。