MyBatis各种查询功能
1.查询一个实体类对象
接口方法 SelectMapper.java
//通过id进行查询
User selectById(@Param("id") int id);
映射文件 SelectMapper.xml
<!--User selectById(int id);-->
<select id="selectById" resultType="user">
select * from user where id = #{id}
</select>
测试类
@Test
public void testSelectbyid(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mappera = sqlSession.getMapper(SelectMapper.class);
User user = mappera.selectById(1);
System.out.println(user);
}
2.查询一个List集合
//查询所有用户
List<User> selectAll();
<!--List<User> selectAll();-->
<select id="selectAll" resultType="user">
select * from user
</select>
3.查询单个数据
/**
* 查询用户的总记录数
* @return
* 在MyBatis中,对于Java中常用的类型都设置了类型别名
* 例如:java.lang.Integer-->int|integer
* 例如:int-->_int|_integer
* 例如:Map-->map,List-->list
*/
int getCount();
resultType的结果为int 直接写他自己设置的类型别名int就行
<!--int getCount();-->
<select id="getCount" resultType="int">
select count(*) from user
</select>
4.查询一条数据为map集合
int getCount();
//返回map id查询
Map<String,Object> findById(@Param("id") int id);
<!--Map<String,Object> findById(@Param("id") int id);-->
<select id="findById" resultType="map">
select * from user where id = #{id}
</select>
test类
@Test
public void testfind(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mappera = sqlSession.getMapper(SelectMapper.class);
System.out.println(mappera.selectById(6));
}
5.查询多条数据为map集合
(1)将map集合放在一个List集合中
//查询所有用户 返回map集合
//将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
List<Map<String,Object>> findAll();
<!--List<Map<String,Object>> findAll();-->
<select id="findAll" resultType="map">
select * from user
</select>
@Test
public void testfindAll(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mappera = sqlSession.getMapper(SelectMapper.class);
for(Map<String,Object> map : mappera.findAll()){
System.out.println(map);
}
}
(2)@MapKey注解设置map集合的键,值是每条数据所对应的map集合
/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的map集合
*/
@MapKey("id")
Map<String, Object> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
<!--
结果:
{
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=张三}
}
-->
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/1246.html
文章版权归作者所有,未经允许请勿转载。
THE END