mybatis 多个主键查询,不存在就新增,存在就更新
时间: 2023-11-30 15:58:08 浏览: 32
可以使用MyBatis的insert和update语句来实现多个主键查询,不存在就新增,存在就更新的功能。
首先,需要在实体类中定义多个主键,例如:
```
public class User {
private int userId;
private String userName;
private String password;
private int age;
// 定义多个主键
@Id
@Column(name = "user_id")
private int userId;
@Id
@Column(name = "user_name")
private String userName;
}
```
然后,在Mapper.xml文件中编写insert和update语句:
```
<!-- 新增用户信息 -->
<insert id="insertUser" parameterType="User">
INSERT INTO user_info (user_id, user_name, password, age)
VALUES (#{userId}, #{userName}, #{password}, #{age})
</insert>
<!-- 更新用户信息 -->
<update id="updateUser" parameterType="User">
UPDATE user_info
SET password = #{password},
age = #{age}
WHERE user_id = #{userId} AND user_name = #{userName}
</update>
```
最后,在Java代码中调用上述方法即可实现多个主键查询,不存在就新增,存在就更新的功能。
```
// 新增用户信息
User user = new User();
user.setUserId(1);
user.setUserName("test");
user.setPassword("123456");
user.setAge(20);
userMapper.insertUser(user);
// 更新用户信息
User user = new User();
user.setUserId(1);
user.setUserName("test");
user.setPassword("654321");
user.setAge(30);
userMapper.updateUser(user);
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![ipynb](https://img-home.csdnimg.cn/images/20210720083646.png)