1.查询一个实体类对象
/*
* 根据用户id查询
* */
User GetUserByID(@Param("id") int id);
<!-- User GetUserByID();-->
<select id="GetUserByID" resultType="com.li.pojo.User">
select * from USER where id=#{id}
</select>
@Test
public void GetUserById(){
SqlSession sqlSession = GetSqlSession.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.GetUserByID(1);
System.out.println(user);
}
2.查询一个list集合
/*
* 查询所有用户信息
* */
List<User> GetAllUser();
<!-- List<User> GetAllUser();-->
<select id="GetAllUser" resultType="com.li.pojo.User">
select * from USER
</select>
@Test
public void GetAllUser(){
SqlSession sqlSession = GetSqlSession.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.getAllUser();
list.forEach(System.out::println);
}
3.查询单个数据
/*
* 查询单个数据,例如总行数
* */
Integer GetCount();
<!-- Integer GetCount();-->
<select id="GetCount" resultType="java.lang.Integer">
select count(*) from user
</select>
@Test
public void GetCount(){
SqlSession sqlSession = GetSqlSession.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Integer integer = mapper.GetCount();
System.out.println(integer);
}
4.查询一条数据为map集合
map集合属性不固定,比如有些属性没有值就不会查询出来
/**
* 根据用户id查询用户信息为map集合
*/
Map<String, Object> getUserToMap(@Param("id") int id);
<!-- Map<String, Object> getUserToMap(@Param("id") int id);-->
<select id="getUserToMap" resultType="map">
select * from user where id=#{id}
</select>
@Test
public void getUserToMap(){
SqlSession sqlSession = GetSqlSession.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = mapper.getUserToMap(1);
System.out.println(map);
}
5.查询多条数据为map集合
方法1
/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此
时可以将这些map放在一个list集合中获取
*/
List<Map<String, Object>> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
方法2
/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并
且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的
map集合
*/
@MapKey("id")
Map<String, Object> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<!--
{
1={password=123456, sex=男, id=1, age=23, username=admin},
2={password=123456, sex=男, id=2, age=23, username=张三},
3={password=123456, sex=男, id=3, age=23, username=张三}
}
-->
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>