forever_2h mybatis 之 占位符#{} 和 ${}

  1. #{}占位符用来设置参数,参数的类型可以有3种,基本类型,自定义类型,map基本类型作为参数,参数与占位符中的名称无关。
    <select id="findById" parameterType="int" resultType="cn.wh.vo.Role">
            select * from t_role where id = #{xxxid}
        </select>

    测试:

    @Test
        public void testSelectOne(){
            Role role = (Role)session.selectOne("cn.wh.mapper.RoleMapper.findById",1);
            System.out.println(role.getName());
        }

    自定义类型作为参数,自定义类中需要为为属性提供get方法,如果没有提供get方法,那么会根据占位符中的名称去反射获取值,如果占位符中的名称和属性不一致,那么报ReflectionException。

    <select id="findListBypage" parameterType="cn.wh.util.PageUtil" resultType="Role">
            select * from t_role limit #{index},#{size}
        </select>

    测试:

    复制代码
    @Test
        public void testPage1(){
            PageUtil pu = new PageUtil();
            pu.setIndex(3);
            pu.setSize(3);
            List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findListBypage", pu);
            for(Role r:list){
                System.out.println(r.getName());
            }
        }
    复制代码

    Map作为参数类型,key和占位符中的名称一致即可,如果名称不一致那么将会把null,传递到占位符中。

    注意:#{}占位符不能解决一下 3 类问题:

    表名是动态的: Select * from #{table_name}

    列名是动态的:Select #{column_name} from t_role

    排序列是动态的: Select * from t_role order by #{columu}

 

 

${}占位符是字符串连接符,可以用来动态设置表明,列名,排序名

${}参数不能为基本数据类型,只能为自定义类型和map

<!-- 查询所有 -->
    <select id="findAll" parameterType="map" resultType="cn.wh.vo.Role">
        select * from ${tableName}
    </select>

测试:

复制代码
@Test
    public void testSelectList(){
        Map<String,String> map = new HashMap<String,String>();
        map.put("tableName", "t_role");
        List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.findAll",map);
        for(Role role:list){
            System.out.println(role.getId()+"----"+role.getName());
        }
    }
复制代码

作为连接符使用:

<select id="selectLike1" parameterType="map" resultType="Role">
        select *from t_role where name like '${name}%';
    </select>

测试:

复制代码
@Test
    public void testLike2(){
        Map<String,String> map = new HashMap<String,String>();
        map.put("name", "");
        List<Role> list = session.selectList("cn.wh.mapper.RoleMapper.selectLike1",map);
        for(Role r:list){
            System.out.println(r.getName());
        }
    }
复制代码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值