ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
转:爱信-韩晓彤 ## 一.Mybatis实体属性与数据库表列名映射的四种方法 ### 1. 通过xml映射文件resultMap ~~~ <mapper namespace="data.UserMapper"> <resultMap type="data.User" id="userResultMap"> <!-- 用id属性来映射主键字段 --> <id property="id" column="user_id"/> <!-- 用result属性来映射非主键字段 --> <result property="userName" column="user_name"/> </resultMap> </mapper> ~~~ 通过里面的id标签和result标签来建立映射关系,由property和column分别指定实体类属性和数据表的列名。 ### 2. 通过注解 @Results 和 @Result > 这两个注解是与XML文件中的标签相对应的: > @Results对应resultMap > @Result对应result **这两个注解是应用在方法的级别上的,也就是在mapper方法上,如下:** ~~~ @Select("select * from t_user where user_name = #{userName}") @Results( @Result(property = "userId", column = "user_id"), @Result(property = "userName", column = "user_name") ) User getUserByName(@Param("userName") String userName); ~~~ 由于注解是针对方法的,对于Mapper中的每个操作数据库的方法都必须有相同的注解完成映射关系的建立,导致很多的配置是重复的; * 缺点: 如果要避免配置重复的问题,可以采用在XML配置文件中配置这个resultMap,然后再@Result中通过id属性引用这个resultMap, 但是这样感觉很麻烦(由于使用了两种配置方式),不如直接使用基于XML的resultMap配置方式; ### 3. 通过属性配置完成映射(推荐) > 驼峰命名法(Camel-Case): > 当变量名或函式名是由一个或多个单字连结在一起,而构成的唯一识别字时,首字母以小写开头,每个单词首字母大写(第一个单词除外)。如userName Mybatis给我们提供了一种映射方式,如果属性的命名是遵从驼峰命名法的,数据列名遵从下划线命名 > 那么可以使用这种方式,类似如下: > userName对应user_name; > userId对应user_id; 配置代码如下: ~~~ SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); Configuration configuration = new Configuration(); configuration.setMapUnderscoreToCamelCase(true); sqlSessionFactoryBean.setConfiguration(configuration); ~~~ ### 4.通过使用SQL字段别名完成映射 这种方式最直接,直接在SQL语句中建立别名来完成映射,如下: ~~~ @Select("select user_name as userName, user_id as userId from t_user where user_name = #{userName}")User getUserByName(@Param("userName") String userName); ~~~ 参考 :http://blog.csdn.net/lmy86263/article/details/53150091 ## 二.在SpringBoot中完成mybatis自动扫描及属性映射 1. mapper自动扫描 增加@MapperScan配置(注意请遵守工程目录文件夹规范) ~~~ @SpringBootApplication @MapperScan(basePackages = {"net.aexit.infrastructure.*.mapper"}) public class InfrastructureApplication { public static void main(String[] args) { SpringApplication.run(InfrastructureApplication.class, args); }} ~~~ 2, 驼峰标示自动映射 **通过对四种映射方法比较,我们认为第三种是最规范,最有效率的!** 只需在application.properties增加配置即可! ~~~ mybatis.configuration.mapUnderscoreToCamelCase=true ~~~ 参考: http://www.cnblogs.com/zhangdong92/p/6986653.html ## 三.在SpringBoot中完成mybatis-plus自动扫描及属性映射 通常我们的项目中会使用mybatis-plus,使用分页插件 0. maven 引入 ~~~ <!-- mybatis-plus begin --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>${mybatisplus-spring-boot-starter.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatisplus.version}</version> </dependency> <!-- mybatis-plus end --> ~~~ 1. 配置mybatis-plus 将MapperScan配置由Application放到mybatis-plus配置上 ~~~ @Configuration @MapperScan(basePackages = {"net.aexit.infrastructure.*.mapper"}) public class MybatisPlusConfig { /** * mybatis-plus分页插件<br> * 文档:http://mp.baomidou.com<br> */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } } ~~~ 2. 修改配置文件 mybatis配置换成mybatis-plus ~~~ mybatis-plus: configuration: mapUnderscoreToCamelCase: true ~~~ 3. 使用分页插件 mapper接口定义 ~~~ List<SysUser> listUser(@Param("userId")String userId, @Param("userName")String userName, @Param("orgId")String orgId, @Param("phone")String phone, @Param("sex")Byte sex, @Param("email")String email, Page<SysUser> page); ~~~ mapper的xml定义,就是简单的select,不含分页,分页由plus完成 ~~~ <select id="listUser" resultType="net.aexit.infrastructure.common.model.SysUser"> SELECT <include refid="Base_Column_List" /> FROM sys_user </select> ~~~ 调用 Page<SysUser> page = new Page<>(pageNo,pageSize); List<SysUser> sysUsers = sysUserExtMapper.listUser(userId,userName,orgId,phone,sex,email,page);、 ## 4. 返回List<Map> ~~~ <select id="selectByDetectSn" resultType="java.util.HashMap"> SELECT r.vehicle_no,report.loc_edit_time,report.detect_result,report.id FROM eds_detection_record r INNER JOIN eds_detection_report report ON r.detect_sn = report.detect_sn WHERE r.vehicle_no IN (SELECT a.vehicle_no FROM app_vehicle a WHERE a.user_id = #{userId}) <if test="vehicleNo != null"> AND r.vehicle_no LIKE "%"#{vehicleNo,jdbcType=VARCHAR}"%" </if> ORDER BY loc_edit_time DESC ; </select> ~~~ ~~~ List<Map<String,Object>> selectByDetectSn(@Param("userId")String userId, @Param("vehicleNo")String vehicleNo); ~~~ ~~~ /** * 获取检测结果 * @param userId * @param vehicleNo * @return */ public List<Map<String,Object>> getByDetectSn(String userId, String vehicleNo){ return edsDetectionRecordMapper.selectByDetectSn(userId,vehicleNo); } ~~~ ~~~ /** * 检测结果 */ @RequestMapping(value = "/detectedRecord", method = RequestMethod.GET) @ResponseBody public AjaxCommonObject detectedRecord(@RequestParam("userId") String userId, @RequestParam(required = false) String vehicleNo) { AjaxCommonObject ajaxCommonObject = new AjaxCommonObject(); try { ajaxCommonObject.setData(bizService.getByDetectSn(userId,vehicleNo)); } catch (BizCommonException e) { return new AjaxCommonObject(e); } return ajaxCommonObject; } ~~~ ![](https://box.kancloud.cn/0aca0db2d48fb1d9dc2584d64c8680f2_797x525.png)