User getUserById(@Param("id") int id);
<select id="getUserById" resultType="User">
select * from t_user where id=#{id}
select>
@Test
public void testGetUserById(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
User user = mapper.getUserById(4);
System.out.println(user);
}
User getUserById(@Param("id") int id);
<select id="getUserList" resultType="User">
select * from t_user
select>
//查询一个List集合
@Test
public void testGetUserL(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
List<User> list = mapper.getUserList();
System.out.println(list);
}
//查询用户总数(总记录数)
int getCount();
<select id="getCount" resultType="_int">
select count(id) from t_user
select>
注:在MyBatis中,Java中常用的类型的类型别名百度即可
3. test测试文件中(SelectMapperTest)
//查询单个数据
@Test
public void testGetCount(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
int a = mapper.getCount();
System.out.println(a);
}
//根据用户id查询用户信息为map集合
Map<String, Object> getUserToMap(@Param("id") int id);
<select id="getUserToMap" resultType="map">
select * from t_user where id=#{id}
select>
//查询User实体类对象
@Test
public void testGetUserToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
Map map = mapper.getUserToMap(4);
System.out.println(map);
}
此时可以将这些map放在一个list集合中获取:
//查询所有用户信息为map集合
List<Map<String, Object>> getAllUserToMap();
<select id="getAllUserToMap" resultType="map">
select * from t_user
select>
//查询所有用户信息为map集合
@Test
public void testGetAllUserToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
List<Map<String,Object>> list = mapper.getAllUserToMap();
System.out.println(list);
}
此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
//查询所有用户信息为map集合
@MapKey("id")
Map<String, Object> getAllUserToMap2();
注意:此时@MapKey(“id”)中的id仅仅是设置id为Map的键,不要理解为方法参数。
2. mapper映射文件中(SelectMapper.xml)
<select id="getAllUserToMap2" resultType="map">
select * from t_user
select>
//查询所有用户信息为map集合
@Test
public void testGetAllUserToMap2(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
Map map = mapper.getAllUserToMap2();
System.out.println(map);
}
本文主要参考:
【尚硅谷】2022版MyBatis教程(细致全面,快速上手)