增删改查标签
- select
id属性:当前名称空间下的statement的唯一标识,要求id必须和mapper接口中的方法的名字一致
resultType:将结果集映射为Java的对象类型,也可以写resultMap(返回的一个集合,可以自定义的类型)
parameterType:传入参数类型,当传一个值时可以省略,传对象时不要省略 - insert
id:唯一标识,在同一个命名空间下保持唯一,使用动态代理之后要求和方法名保持一致
parameterType:参数的类型,使用动态代理之后和方法的参数类型一致
useGenerateKeys:开启主键回写
keyColumn:指定数据库的主键
keyProperty:主键对应的pojo属性名
标签内部:具体的sql语句 - update
id:当前名称空间下的statement的唯一标识符
parameterType:传入的参数类型,可以省略
标签内部:具体的sql语句 - delete
id:当前名称空间下的statement的唯一标识符
parameterType:传入的参数类型,可以省略
标签内部:具体的sql语句
#和&的应用
- # { }特点
在参数是一个非POJO类型时,该值可以是任何内容,只是负责占位;#{}是预编译处理,相当于PreparedStatement使用?占位符去替换参数,防止sql注入,
书写方式:
select * from user where username like "%"#{username}"%";
insert into user (username,password,age,sex,hobby,remark) values (#{username},#{password},#{age},#{sex},#{hobby},#{remark});
- $ { }特点
是字符串拼接,相当于sql语句中的Statement ,使用字符串去拼接sql,$可以是sql中任意部分传入到Statement 中,不能防止sql注入,大括号中必须写value(一个值时)
书写方式:
select * from user where username like '%${value}%' ;
insert into user (username,password,age,sex,hobby,remark) values ('${username}','${password}','${age}','${sex}','${hobby}','${remark}');
sql注入示例:select * from user where id = 1 or 1=1
ResultMap
ResultMap是Mybatis中最重要最强大的元素,使用ResultMap可以解决两大问题:
- POJO属性名和表结构字段名不一致的问题
- 完成高级查询,比如一对一、一对多、多对多
<resultMap type="org.mybatis.vo.UserVO" id="UserVO1ResultMap" autoMapping="true">
<select id="selectUserListByNameLike" resultMap="UserVO1ResultMap" parameterType="string">
select * from user where username like "%"#{username}"%"
</select>
resultMap 会自动把查询的结果的列名与Java类型中的属性进行匹配,匹配成功了就把值封装到对象上,没有匹配成功的就是null或0。为了解决这个问题,会对result或者id进行一一对应,主键使用id标签,其他内容全都是result
<resultMap type="org.mybatis.vo.UserVO" id="UserVO1ResultMap" autoMapping="true">
<!--主键对应-->
<id column="userid" property="id"/>
<!--非主键对应-->
<result column="username" property="username"/>
<result column="userpassword" property="password"/>
<result column="userage" property="age"/>
<result column="usersex" property="sex"/>
</resultMap>
<select id="selectUserListByNameLike" resultMap="UserVO1ResultMap" parameterType="string">
select * from user where username like "%"#{username}"%"
</select>
Sql片段
经常使用的sql片段可以单独拿出来
<sql id=""></sql>
<include refId=""/>
例如
<sql id="userComm">
id,username,password,age,sex
</sql>
<select id="selectUserListByNameLike" resultMap="UserVO1ResultMap" parameterType="string">
select <include refId="userComm"/></include> from user where username like "%"#{username}"%"
</select>
建议sql片段单独放在一个commSql.xml文件里
需要在配置文件中引用通用文件
<mapper resource="org/mybatis/dao/sqlComm.xml"/>