mybatis怎么实现根据主键Id,修改学生信息记录
时间: 2023-06-12 15:06:53 浏览: 74
MyBatis 实现根据主键 ID 修改学生信息记录,通常有以下几个步骤:
1. 在 StudentMapper.xml 文件中编写 SQL 语句,使用 UPDATE 关键字,指定要修改的表名和 SET 关键字,设置要修改的字段值,使用 WHERE 关键字指定要修改的记录的主键 ID。
示例代码如下:
```xml
<!-- 根据主键 ID 修改学生信息记录 -->
<update id="updateStudentById" parameterType="com.example.Student">
UPDATE student
SET name = #{name},
age = #{age},
gender = #{gender}
WHERE id = #{id}
</update>
```
2. 在 StudentMapper 接口中定义一个方法,方法名称和参数列表要和 StudentMapper.xml 中定义的 SQL 语句对应。
示例代码如下:
```java
public interface StudentMapper {
// 根据主键 ID 修改学生信息记录
int updateStudentById(Student student);
}
```
3. 在 Java 代码中调用 StudentMapper 接口的 updateStudentById() 方法,传入要修改的学生信息记录对象。
示例代码如下:
```java
// 创建 SqlSession 对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取 StudentMapper 接口的代理对象
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
// 创建要修改的学生信息记录对象
Student student = new Student();
student.setId(1); // 设置要修改的记录的主键 ID
student.setName("张三"); // 设置要修改的记录的姓名
student.setAge(20); // 设置要修改的记录的年龄
student.setGender("男"); // 设置要修改的记录的性别
// 调用 updateStudentById() 方法,修改学生信息记录
int rows = studentMapper.updateStudentById(student);
// 提交事务
sqlSession.commit();
// 关闭 SqlSession
sqlSession.close();
```
注意事项:
- SQL 语句中的表名和字段名要和数据库中的实际情况一致。
- StudentMapper.xml 文件中的 SQL 语句的 id 属性值要和 StudentMapper 接口中的方法名一致。
- StudentMapper 接口中的方法参数类型要和 SQL 语句中的参数类型一致。
- 修改操作需要提交事务,否则修改不会生效。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)