Mybatis总结

1、ResultMap与ResultType的区别

ResultMap:表示将查询结果集中的列一一映射到bean对象的各个属性

<resultMap type="User" id="baseResult">
    <id column="user_ame" property="username">
    <id column="user_id" property="userid">
</resultMap>
<select id="getUser" resultMap="baseResult">
    select * from user where user_id=#{user_id} and user_name=#{user_name}
</selece>

ResultType:表示的bean中的对象类,必须保证查询结果集中的属性和bean对象类的属性是一一对应的。

<select id="getUser" resultType="User">
    select * from user where user_id=1
</selece>

resultMap与resultType不能同时存在。

parameterType:直接将查询结果列值类型自动对应到对象属性类型上,不需要配置对应关系。
parameterMap:与resultMap类似(不推荐)

2、mabatis中 # 和 $ 的区别

  • #:在预编译是会提供一个占位符?,如select * from user where user_id = #{userid}转换成select * from user where user_id = ?,将传入的数据当成一个字符串,若传入数据为1,则sql语句就会变成select * from user where user_id = 1.
  • $:直接将传入的数据拼接在后面,如select * from user where user_name = ${username},传入数据为username,则sql语句变成:select * from user where user_name = username。
  • #{}的方式能有效防止sql注入,而${}方式不能防止。

3、 xml映射文件中,除了insert、update、select、delete之外还有哪些标签

< resultMap>,< parameterMap>,< sql>,< include>,< selectKey>,加上动态sql的9个标签:trim,where,set,foreach,if,when,otherwise,bind等,其中< sql >为sql片段标签,通过< include>标签引入sql片段,< selectKey>为不支持自增的主键生成策略标签。

4、最佳实践中,一个xml文件通常都会写一个Dao接口与之对应,这个Dao接口的工作原理是什么?Dao接口里,参数不同时,方法能重载吗?

dao接口也就是mapper接口,接口的全限名就是xml映射文件中的namespace值,接口的方法名就是xml映射文件中的MappedStatement的id值,接口方法内的参数就是传递给sql语句的参数,dao接口是没有实现类的,当调用接口方法时,接口全限名+方法名拼接为字符串作为key值可以定位一个唯一的MappedStatement。如mapper.java中UserDao(全限名).findUser(方法名)可以找到namespace为mapping.xml中id=findUser的MappedStatement。
dao接口的工作原理是JDK动态代理,Mybatis运行时会使用jdk动态代理为dao接口生成proxy动态代理对象,代理对象会拦截接口方法,转而执行MappedStatement所代表的sql,然后将sql执行后的结果返回。
dao接口力的方法是不能重载的。

分页查询

简单分页查询:如 select * from user limit 0,10,或有条件的:select * from user where user_name = #{username} limit 0,10
动态sql:如
<select * from user>
<where>
<if test = 'userid != null'>
and user_id = #{userid}
</if>
<if test = 'username != null'>
and user_name = #{username}
</if>
</where>
</select>
<set>标签,其中判断条件aa=#{aa}后面需要带“,”,set标签会自动取出最后一个逗号。
<foreach>标签,foreach用于遍历数组,open表示开始符号,close表示结束符号,separator表示中间分隔符,item表示数组参数。
<delete id = "deleteUser">
<foreach collection = "array" open="(" close=")" separator="," item = "id">
#{id}
</foreach>
</delete>

mybatis的xml文件中,不同的xml文件,id是否可以重复

不同的xml映射文件,如果配置了namespace,那么id是可以重复的,如果没有配置,id是不能重复的,此时id重复会导致数据覆盖,引发错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值