public class Employee { private Integer id; private String lastName; private String email; private String gender;
//setter与getter省略
}
而数据库中的 last_name字段是这样的与实体不一致
@Test public void test05() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try{ EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class); Employee empById = mapper.getEmpById(1); System.out.println(empById); /*Employee empAndDept = mapper.getEmpAndDept(1); System.out.println(empAndDept); System.out.println(empAndDept.getDept());*/ // Employee employee = mapper.getEmpByIdStep(3); // System.out.println(employee); //System.out.println(employee.getDept()); //System.out.println(employee.getDept()); }finally{ openSession.close(); } }
在xml里这样配置的
<!-- public Employee getEmpById(Integer id); --> <select id="getEmpById" resultType="com.atguigu.mybatis.bean.Employee"> select * from tbl_employee where id=#{id} </select>
因为属性和字段不一致对应查询结果如图
导致了lastName没有附上值
如何解决呢,可以在mybaits-confg.xml配置驼峰命名就能解决这一个问题,但是很局限性
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="jdbcTypeForNull" value="NULL"/> <!--显示的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings>
接下来讲解用resultMap解决这一个问题
<resultMap type="com.atguigu.mybatis.bean.Employee" id="MySimpleEmp"> <!--指定主键列的封装规则 id定义主键会底层有优化; column:指定哪一列 property:指定对应的javaBean属性 --> <id column="id" property="id"/> <!-- 定义普通列封装规则 --> <result column="last_name" property="lastName"/> <!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 --> <result column="email" property="email"/> <result column="gender" property="gender"/> </resultMap>
<!-- public Employee getEmpById(Integer id); --> <select id="getEmpById" resultMap="MySimpleEmp"> select * from tbl_employee where id=#{id} </select>
执行结果如下:
|