MyBatis XML一个方法执行插入或更新操做(PostgreSQL)

MyBatis XML一个方法执行插入或更新操做(PostgreSQL)

在MyBatis中,你可以使用PostgreSQL的INSERT ... ON CONFLICT子句来实现插入或更新(即"upsert")操作。以下是一个示例,展示如何在MyBatis中配置和执行这样的操作。

PostgreSQL SQL 示例

假设你有一个表users,包含以下字段:

id (主键)

name

email

你希望在插入数据时,如果id已经存在,则更新相应的name和email字段。

SQL语句可能如下:

sql 复制代码
INSERT INTO users (id, name, email)
VALUES (1, '黎明', '123@163.com')
ON CONFLICT (id) DO UPDATE
SET name = '黎明',
    email = '123@163.com';

MyBatis Mapper XML 配置

首先,定义你的MyBatis Mapper XML文件,比如UserMapper.xml:

xml 复制代码
<?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.mapper.UserMapper">

  <insert id="insertAndUpdate" parameterType="com.example.model.User">
    INSERT INTO users
    <trim prefix="(" suffix=")" suffixOverrides=",">
    	<if test="id!=null">
        	id,
        </if>
        <if test="name!=null and name!=''">
        	name,
        </if>
        <if test="email!=null and email!=''">
        	email,
        </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
        <if test="id!= null">
            #{id},
        </if>
        <if test="name!=null and name!=''">
            #{name},
        </if>
        <if test="email!=null and email!=''">
            #{email},
        </if>
    </trim>
    ON conflict(id)
    DO UPDATE SET
    <trim prefix="" suffix="" suffixOverrides=",">
        <if test="id!=null">
            id=#{id},
        </if>
        <if test="name!=null and name!=''">
        	name=#{name},
        </if>
        <if test="email!=null and email!=''">
        	email=#{email},
        </if>
    </trim>
  </insert>

</mapper>

MyBatis Mapper 接口

接下来,定义对应的Mapper接口,比如UserMapper.java:

java 复制代码
package com.example.mapper;

import com.example.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper {
    // 或者,如果你使用XML配置,可以省略注解,方法签名要匹配XML中的id
    void insertAndUpdate(User user);

	// 或者,你可以直接在接口上写sql
    @Insert("INSERT INTO users (id, name, email) VALUES (#{id}, #{name}, #{email}) ON CONFLICT (id) DO UPDATE SET name = #{name}, email = #{email}")
    void upsertUser(User user);
}

注意:ON CONFLICT子句中的冲突字段(id)必须是表的主键或有唯一约束的字段

相关推荐
invicinble16 小时前
spring相关系统性理解,企业级应用
java·spring·mybatis
gAlAxy...20 小时前
MyBatis 核心配置文件 SqlMapConfig.xml 全解析
xml·mybatis
endcy20161 天前
多路召回之-PGSQL的关键词检索分词插件安装
人工智能·ai·postgresql
2501_916766541 天前
【Mybatis】延迟加载与多级缓存
缓存·mybatis
QQ 19226381 天前
基于LabVIEW语言的ABB上位机Demo:获取日志、设备信息、速度与状态功能介绍
postgresql
雪域迷影1 天前
完整的后端课程 | NodeJS、ExpressJS、JWT、Prisma、PostgreSQL
数据库·postgresql·node.js·express·prisma
YDS8292 天前
MyBatis-Plus精讲 —— 从快速入门到项目实战
java·后端·spring·mybatis·mybatis-plus
库库林_沙琪马2 天前
7、集成MyBatis
spring boot·mybatis
2501_916766542 天前
【Mybatis】注解开发与事务
mybatis
少年攻城狮2 天前
Mybatis-Plus系列---【自定义拦截器实现sql完整拼接及耗时打印】
数据库·sql·mybatis