尚硅谷面试第一季-11MyBatis中当实体类中的属性名和表中的字段名不一样怎么办

问题:

MyBatis中当实体类中的属性名和表中的字段名不一样 ,怎么办 ?

解决方案:

1.写sql语句时起别名

1 <!-- id属性:必须是接口中方法的方法名
2 resultType属性:必须是方法的返回值的全类名-->
3 <select id="getEmployeeById" resultType="MyBatis中当实体类中的属性名和表中的字段名不一样怎么办.entities.Employee">
4 select id,last_name lastName,email,salary,dept_id deptId from employees where id = #{id}</select>

2.在MyBatis的全局配置文件中开启驼峰命名规则 

1 <settings>
2 <!-- 开启驼峰命名规则 ,可以将数据库中的下划线映射为驼峰命名
3 例如:last_name可以映射为lastName -->
4 <setting name="mapUnderscoreToCamelCase" value="true"/>
5 </settings>

3.在Mapper映射文件中使用resultMap来自定义映射规则

 1 <select id="getEmployeeById" resultMap="myMap">
 2         select * from employees where id = #{id}
 3     </select>
 4     
 5     <!-- 自定义高级映射 -->
 6     <resultMap type="MyBatis中当实体类中的属性名和表中的字段名不一样怎么办.entities.Employee" id="myMap">
 7         <!-- 映射主键 -->
 8         <id column="id" property="id"/>
 9         <!-- 映射其他列 -->
10         <result column="last_name" property="lastName"/>
11         <result column="email" property="email"/>
12         <result column="salary" property="salary"/>
13         <result column="dept_id" property="deptId"/>
14     </resultMap>

测试用例:

 1 //1.MyBatis中当实体类中的属性名和表中的字段名不一样 ,怎么办 ?
 2     /*
 3      * 解决方案:
 4      *     1.写sql语句时起别名
 5      *     2.在MyBatis的全局配置文件中开启驼峰命名规则
 6      *  3.在Mapper映射文件中使用resultMap来自定义映射规则
 7      */
 8     
 9     @Test
10     void testGetEmployee() throws IOException {
11         //1.创建SqlSessionFactory对象
12         String resource = "mybatis-config.xml";
13         InputStream inputStream = Resources.getResourceAsStream(resource);
14         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
15         //2.获取sqlSession,sqlSession就相当于JDBC中的connection
16         SqlSession sqlSession = sqlSessionFactory.openSession();
17         try {
18           //3.获取Mapper对象
19           EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
20           //4.调用EmployeeMapper中获取Employee的方法
21           Employee employee = mapper.getEmployeeById(1);
22           System.out.println(employee);
23         } finally {
24           //5.关闭sqlSession
25           sqlSession.close();
26         }

运行结果:

完整代码:

https://gitee.com/ZhangShunHai/interview_atguigu_seasonone/tree/master/ssm_mybatis%20mapping

posted @ 2019-03-29 16:01  张顺海  阅读(565)  评论(0编辑  收藏  举报