mybatis 多个主键查询,不存在就新增,存在就更新
时间: 2023-11-30 07:58:08 浏览: 26
可以使用MyBatis的`<selectKey>`标签和`<insert>`标签来实现多个主键查询、不存在就新增、存在就更新的功能。
首先,定义一个Mapper接口,包含一个方法用于查询:
```java
public interface MyMapper {
MyEntity selectByKeys(@Param("key1") String key1, @Param("key2") String key2);
}
```
然后,在MyBatis的映射文件中,使用`<selectKey>`标签来查询数据,如果查询结果为空,则使用`<insert>`标签来新增数据,否则使用`<update>`标签来更新数据:
```xml
<select id="selectByKeys" resultMap="myResultMap">
select * from my_table where key1 = #{key1} and key2 = #{key2}
<selectKey keyProperty="key1" order="BEFORE">
select #{key1} from dual where not exists (select 1 from my_table where key1 = #{key1} and key2 = #{key2})
</selectKey>
<selectKey keyProperty="key2" order="BEFORE">
select #{key2} from dual where not exists (select 1 from my_table where key1 = #{key1} and key2 = #{key2})
</selectKey>
<insert id="insert" parameterType="MyEntity">
insert into my_table (key1, key2, value) values (#{key1}, #{key2}, #{value})
</insert>
<update id="update" parameterType="MyEntity">
update my_table set value = #{value} where key1 = #{key1} and key2 = #{key2}
</update>
</select>
```
在查询时,先调用`selectByKeys`方法,如果查询结果为空,则会先执行`<selectKey>`标签,判断数据是否存在,如果不存在,则会执行`<insert>`标签来新增数据,否则会执行`<update>`标签来更新数据。最终返回查询结果。
注意,`<selectKey>`标签必须放在`<select>`标签内部,且order属性必须设置为BEFORE,表示在执行查询之前执行。同时,keyProperty属性必须设置为实体类中对应主键的属性名,以便在新增或更新时使用。