在mybatis中有一个resultMap标签,它是为了映射select查询出来的结果的集合,其主要作用是将实体类中的字段与数据库表中的字段进行关联映射。当实体类中的字段与数据库表中的字段相同时,可以将resultMap标签中的关联关系忽略不写。当实体类中的字段与数据库表中的字段不相同时,就需要在resultMap标签中将实体类字段与数据库字段一一进行关联映射,或者开启驼峰规则,让它自动转换。
使用resultMap,就要禁用驼峰规则。如果不想改实体类的话,可以采用resultMap。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--在mybatis中,映射文件中的namespace是用于绑定dao接口的,即面向接口编程。当你的namespace绑定接口后,可以不用写接口实现类 mybatis会通过绑定自动帮你找到对应要执行的sql语句--> <!-- xmlns="http://mybatis.org/schema/mybatis-mapper" --> <mapper namespace="com.example.page.mapper.UserMapper"> <!--在mybatis中有一个resultMap标签,它是为了映射select查询出来结果的集合,其主要作用是将实体类中的字段与数据表中的字段进行关联映射 注意 当实体类中的字段与数据库表中的字段相同时,可以将resultMap标签中的关联关系忽略不写 当实体类中的字段与数据库中的字段不相同时,就需要在resultMap标签中将实体类字段与数据库字段一一进行关联映射,或者开启驼峰规则,让它自动转换 --> <resultMap id="result" type="com.example.page.entity.User"> <result property="userId" column="userId"/> <result property="userDate" column="userDate"/> <result property="userName" column="userName"/> <result property="userAddress" column="userAddress"/> </resultMap> <!-- ListUser--> <select id="ListUser" resultMap="result"> select * from user </select> <!-- 在Mapper.xml中可以通过#{}获取参数: parameterType控制参数类型 #{}获取参数内容: 1:使用索引,从0开始#{0}表示第一个参数 2:也可以使用#{param1}第一个参数 3:如果参数时对象#{属性名} 4:如果参数是map写成#{key} #{}和${}的区别: #{}获取参数的内容支持,索引获取,param1获取指定位置参数,并且sql使用?占位符,${}字符串拼接不使用?,默认找${内容}内容的get/set方法 --> <!-- findUserByName--> <select id="findUserByName" resultMap="result" parameterType="String"> select * from user where userName like concat(concat('%',#{userName}),'%') order by userId desc </select> <!-- queryPage--> <select id="queryPage" resultMap="result" parameterType="Integer"> select * from user order by userId desc limit #{startRows},5 </select> <!-- select count(*):查询所有行 select count(0):忽略所有列,统计行数,与列无关--> <!-- getRowCount--> <select id="getRowCount" resultType="Integer"> select count(*) from user </select> <!-- insertUser--> <insert id="insertUser" parameterType="com.example.page.entity.User"> insert into user (userId,userDate,userName,userAddress) values (#{userId},#{userDate},#{userName},#{userAddress}) </insert> <!-- delete--> <delete id="delete" parameterType="int"> delete from user where userId = #{userId} </delete> <!-- update--> <update id="Update" parameterType="com.example.page.entity.User"> update user set user.userDate=#{userDate},user.userName=#{userName},user.userAddress=#{userAddress} where user.userId=#{userId} </update> </mapper>
mybatis的mapper.xml中resultMap标签的使用详解
猜你喜欢
转载自blog.csdn.net/li_w_ch/article/details/109066940
今日推荐
周排行