一、查询一个实体类对象
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 ( 1 ) ;
System . out. println ( user) ;
}
二、查询一个list集合
当查询的数据为多条时,不能使用实体类作为返回值,否则会抛出异常TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值
List < User > getAllUser ( ) ;
< select id = " getAllUser" resultType = " User" >
select * from tb_user;
</ select>
@Test
public void testGetAllUser ( ) {
SqlSession sqlSession = SqlSessionUtils . getSqlSession ( ) ;
SelectMapper mapper = sqlSession. getMapper ( SelectMapper . class ) ;
List < User > list = mapper. getAllUser ( ) ;
list. forEach ( System . out:: println ) ;
}
三、查询单个数据
int getCount ( ) ;
< select id = " getCount" resultType = " int" >
select count(*) from tb_user;
</ select>
@Test
public void testGetCount ( ) {
SqlSession sqlSession = SqlSessionUtils . getSqlSession ( ) ;
SelectMapper mapper = sqlSession. getMapper ( SelectMapper . class ) ;
Integer count = mapper. getCount ( ) ;
System . out. println ( count) ;
}
四、查询一条数据为map集合
Map < String , Object > getUserByIdToMap ( @Param ( "id" ) Integer id) ;
< select id = " getUserByIdToMap" resultType = " map" >
select * from tb_user where id = #{id};
</ select>
@Test
public void testGetUserByIdToMap ( ) {
SqlSession sqlSession = SqlSessionUtils . getSqlSession ( ) ;
SelectMapper mapper = sqlSession. getMapper ( SelectMapper . class ) ;
Map < String , Object > map = mapper. getUserByIdToMap ( 1 ) ;
System . out. println ( map) ;
}
五、查询多条数据为map集合
@MapKey ( "id" )
Map < String , Object > getAllUserToMap ( ) ;
< select id = " getAllUserToMap" resultType = " map" >
select * from tb_user
</ select>
@Test
public void testGetAllUserToMap ( ) {
SqlSession sqlSession = SqlSessionUtils . getSqlSession ( ) ;
SelectMapper mapper = sqlSession. getMapper ( SelectMapper . class ) ;
Map < String , Object > map = mapper. getAllUserToMap ( ) ;
System . out. println ( map) ;
}