Mybatis⽤xml配置sql传参⽅式1、传⼊⼀个参数
⽅法:
int deleteByPrimaryKey(Integer id);
配置
<delete id="deleteByPrimaryKey"parameterType="java.lang.Integer">
delete from t_people
where id = #{id,jdbcType=INTEGER}
</delete>
这⾥⾯可以直接⽤#{id}在sql语句中写。
2、2、#{0}、#{1}……索引⽅式,传⼊多个参数
public User selectUserByNameAndAge(String name,int age);
<select id="selectUserByNameAndAge"resultType="user">
select * from user where name = #{0} and age = #{1}
</select>
这⾥⾯⽤数组索引的形式指代。
3、#{参数名},传⼊多个参数,并且参数⽤@param注解
public User selectUserByNameAndAge(@param("name")String name,@param("age")int age);
<select id="selectUserByNameAndAge"resultType="user">
select * from user where name = #{name} and age = #{age}
</select>
可以根据param名称查询
4、传⼊多个基本类型参数,参数⽤map封装,通过#{mapKey}取值
public User selectUserByNameAndAge(Map map);
<select id="selectUserByNameAndAge"parameterType="Map"resultType="user">
select * from user where name = #{name} and age = #{age}
</select>
这⾥的#{mapKey}指的就是#{name}、#{age}
5、使⽤map封装实体类,通过通过#{mapKey.attributeName}取值
public User selectUserByNameAndAge(Map map);
<select id="selectUserByNameAndAge"parameterType="Map"resultType="user">
select * from user where name = #{userParam.name} and age = #{userParam.age}
</select>param name
Service
User userParam =new User("lucy",18);
Map<String,Object> map=new HasMap<String,Object>();
map.put("user",userParam);
User user = userDao.selectUserByNameAndAge(map);
6、直接传⼊实体参数,通过#{属性名}取值
public User selectUserByNameAndAge(User userParam);
<select id="selectUserByNameAndAge" parameterType="User" resultType="user">
select * from user where name = #{userParam.name} and age = #{userParam.age}
</select>
7、使⽤${}
#{}与${}的区别:
{}拿到值之后,拼装sql,会⾃动对值添加单引号”
${}则把拿到的值直接拼装进sql,如果需要加单引号”,必须⼿动添加,⼀般⽤于动态传⼊表名或字段名使⽤,同时需要添加属性statementType=”STATEMENT”,使⽤⾮预编译模式。
public List<User>selectUserByOrgId(String orgId);
<select id="selectUserByOrgId" parameterType="java.lang.String" resultType="user" statementType="STATEMENT">
select * from user where org_id = ${orgId}
</select>
Service
String orgId ="100";
orgId ="'"+ orgId +"'";
List<User> users = userDao.selectUserByOrgId(orgId);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论