MyBatis返回list结果

这部分为转载的

UserDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="myBatisTest.dao.UserDao">

    <!--resultType可以为包加类的model对象 如果返回多条数据,他会返回一个list<UserInfo>的集合-->
    <!--可以使用java.util.Map 但不能直接指定为java.util.List 因为返回的是一个泛型集合list<UserInfo>-->

    <!--resultType的返回类型为POJO类型(list<UserInfo>类型)所以UserDao接口需要保持一致-->
    <select id="getUser" parameterType="UserInfo" resultType="UserInfo">
        select * from userinfo 
        <!--where 加入where语句 也可以在上面语句用 where 1=1之类的 -->
        <where>
            <!--为true则加入下面语句  test内的id是从对象UserInfo中获取的属性值-->
            <if test="id!=0">
            <!--加入了where标签如果是第一个条件,组合语句会自动去掉and-->
                and id=#{id}
            </if>
            <!--语句可以用and(&&)或者or(||)连接-->
            <if test="userName!=null and userName!=''">
            <!--在双引号内 需要把#改为$  ${userName}用于与%%拼接字符串 否则会出现%?%的占位符而出错-->
                and username like '%${userName}%'
            </if>
        </where>
    </select>
</mapper>

test.java

package myBatisTest.dao;

import ....
public class test {
    public static void main(String[] args) throws IOException, SQLException {
        // TODO Auto-generated method stub
        InputStream is = Resources.getResourceAsStream("myBatisTest/dao/SqlMapConfig.xml");
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sf.openSession();
        UserDao ud= sqlSession.getMapper(UserDao.class);//获取代理对象

        List<UserInfo> ulist=ud.getUser(new UserInfo(0,"张","","",""));
        for (int i = 0; i < ulist.size(); i++) {
            System.out.println(ulist.get(i));
        }
    }
}

我的代码

<resultMap id="BaseResultMap" type="com.wjh.bean.TRole" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="rolename" property="rolename" jdbcType="VARCHAR" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, rolename
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_role
    where id = #{id,jdbcType=INTEGER}
  </select>
  <select id="selectAll" resultMap="BaseResultMap" >
    select 
    <include refid="Base_Column_List" />
    from t_role
  </select>
接口中对应的方法:
 List<TRole> selectAll();
 测试:
 @Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private TRoleMapper roleMapper;
    @Override
    public List<TRole> findAllRole() {
        List<TRole> roleList=roleMapper.selectAll();
        return roleList;
    }

}
结果:
TRole [id=1, rolename=用户]
TRole [id=2, rolename=商家]

猜你喜欢

转载自blog.csdn.net/flower_CSDN/article/details/81369974