Mybatis-Plus实践学习(四)

2023-11-26 14:34:04 浏览数 (1)

2.3.3、Mybatis MP实现查询User

第一步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有方法:

代码语言:javascript复制

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
public interface UserMapper extends BaseMapper<User> {
List<User> findAll();
}

第二步,使用MP中的MybatisSqlSessionFactoryBuilder进程构建:

代码语言:javascript复制
public class TestMybatisPlus {
@Test
public void testUserList() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//这里使用的是MP中的MybatisSqlSessionFactoryBuilder
SqlSessionFactory sqlSessionFactory = new
MybatisSqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 可以调用BaseMapper中定义的方法
List<User> list = userMapper.selectList(null);
for (User user : list) {
System.out.println(user);
}
}
}

运行报错:

解决:在User对象中添加@TableName,指定数据库表名

测试:

代码语言:javascript复制
[main] [cn.itcast.mp.simple.mapper.UserMapper.selectList]-[DEBUG] ==> Preparing:
SELECT id,user_name,password,name,age,email FROM tb_user
[main] [cn.itcast.mp.simple.mapper.UserMapper.selectList]-[DEBUG] ==> Parameters:
[main] [cn.itcast.mp.simple.mapper.UserMapper.selectList]-[DEBUG] <== Total: 5
User(id=1, userName=zhangsan, password=123456, name=张三, age=18, email=test1@itcast.cn)
User(id=2, userName=lisi, password=123456, name=李四, age=20, email=test2@itcast.cn)
User(id=3, userName=wangwu, password=123456, name=王五, age=28, email=test3@itcast.cn)
User(id=4, userName=zhaoliu, password=123456, name=赵六, age=21, email=test4@itcast.cn)
User(id=5, userName=sunqi, password=123456, name=孙七, age=24, email=test5@itcast.cn)

简单说明:

由于使用了MybatisSqlSessionFactoryBuilder进行了构建,继承的BaseMapper中的方法就载入到了SqlSession中,所以就可以直接使用相关的方法;

如图:

0 人点赞