mybatis 增删改
时间: 2023-11-07 15:00:45 浏览: 45
MyBatis 是一种优秀的持久化框架,它可以帮助我们更方便地进行数据库操作。下面是 MyBatis 中增删改的示例代码:
1. 插入数据
```java
// 创建一个 User 对象
User user = new User();
user.setName("Alice");
user.setAge(20);
// 插入数据
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insert(user);
sqlSession.commit();
} finally {
sqlSession.close();
}
```
2. 更新数据
```java
// 更新数据
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getById(1);
user.setName("Bob");
userMapper.update(user);
sqlSession.commit();
} finally {
sqlSession.close();
}
```
3. 删除数据
```java
// 删除数据
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.delete(1);
sqlSession.commit();
} finally {
sqlSession.close();
}
```
以上代码中,`UserMapper` 是一个 DAO 接口,它包含了常见的数据库操作方法。MyBatis 会根据接口定义自动生成相应的实现类。其中,`sqlSessionFactory` 是由 MyBatis 配置文件创建的工厂类。
相关推荐
![](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)