sql映射基础
mybatis通过xml或注解方式定义sql映射。xml文件中使用<mapper>
标签声明命名空间,内部通过<select>
、<insert>
、<update>
、<delete>
定义crud操作。例如:
<mapper namespace="com.example.usermapper"> <select id="selectuserbyid" resulttype="user"> select * from users where id = #{id} </select> </mapper>
注解方式直接在接口方法上使用@select
、@insert
等注解:
public interface usermapper { @select("select * from users where id = #{id}") user selectuserbyid(int id); }
动态sql实现
mybatis提供<if>
、<choose>
、<foreach>
等标签实现动态查询。
条件判断:
<select id="findusers" resulttype="user"> select * from users <where> <if test="name != null"> and name = #{name} </if> <if test="age != null"> and age = #{age} </if> </where> </select>
循环处理:
<delete id="deleteusers"> delete from users where id in <foreach item="id" collection="list" open="(" separator="," close=")"> #{id} </foreach> </delete>
高级映射技巧
结果集映射:使用<resultmap>
处理复杂对象关系。例如一对多映射:
<resultmap id="userwithorders" type="user"> <id property="id" column="user_id"/> <collection property="orders" oftype="order"> <result property="orderid" column="order_id"/> </collection> </resultmap>
分页插件:集成pagehelper实现物理分页:
pagehelper.startpage(1, 10); list<user> users = usermapper.selectall(); pageinfo<user> pageinfo = new pageinfo<>(users);
性能优化建议
- 使用
<sql>
标签复用sql片段 - 批量操作优先选择
<foreach>
而非多次单条提交 - 延迟加载关联对象需配置
lazyloadingenabled=true
- 避免n+1查询问题,使用
@many
或@one
注解优化
常见问题排查
- 参数未匹配:检查
#{param}
与接口参数名是否一致 - 结果映射失败:确认
resulttype
或resultmap
配置正确 - sql注入风险:禁止直接拼接
${}
表达式处理用户输入
通过掌握这些核心技巧,可高效利用mybatis完成复杂数据操作。实际开发中建议结合日志工具(如log4j)监控生成的sql语句。
以上就是mybatis中sql映射与动态查询的技巧分享的详细内容,更多关于mybatis sql映射与动态查询的资料请关注代码网其它相关文章!
发表评论