mybatis-test的曾删改查
时间: 2023-06-10 13:09:01 浏览: 48
MyBatis-Test 是一个用于 MyBatis 测试的工具库,它提供了一些实用的测试工具类和方法,可以方便地进行 MyBatis 单元测试。下面是 MyBatis-Test 的增删改查示例:
1. 添加数据
```
@Test
public void testInsert() throws SQLException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setName("Lucy");
user.setAge(18);
user.setGender(1);
userMapper.insert(user);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
```
2. 查询数据
```
@Test
public void testSelect() throws SQLException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.getAllUsers();
for (User user : userList) {
System.out.println(user);
}
} finally {
sqlSession.close();
}
}
```
3. 更新数据
```
@Test
public void testUpdate() throws SQLException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.getUserById(1L);
user.setName("Tom");
user.setAge(20);
user.setGender(0);
userMapper.update(user);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
```
4. 删除数据
```
@Test
public void testDelete() throws SQLException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.delete(1L);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
```
以上是 MyBatis-Test 的基本增删改查操作示例,具体实现还需根据实际情况进行调整。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)