<!--namespace:映射xml接口-->
<mapper namespace="com.itheima.mapper.EmpMapper">
<!-- type: 操作实体类名-->
<!-- 设置主键-->
<!-- result:建立映射关系-->
<!-- property:实体类属性;column:数据库表字段-->
<resultMap id="empResultMap" type="com.itheima.domain.Emp">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="password" column="password"></result>
<result property="name" column="name"></result>
<result property="gender" column="gender"></result>
<result property="image" column="image"></result>
<result property="job" column="job"></result>
<result property="ed" column="ed"></result>
<result property="deptId" column="dept_id"></result>
<result property="createTime" column="create_time"></result>
<result property="updateTime" column="update_time"></result>
</resultMap>
<select id="selectAll" resultMap="empResultMap">
select * from emp
</select>
mappe层
List<Emp> selectAll();
测试类
@Test
public void testResultMap(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
List<Emp> list = mapper.selectAll();
list.forEach(s-> System.out.println(s));
MybatisUtil.close(sqlSession);
}
动态SQL是一种在运行时构建 SQL 查询语句的方法。它允许根据不同的条件和参数来生成不同的查询。
在动态SQL中,你可以根据需要动态地拼接 SQL 语句的各个部分,比如选择要查询的表、指定要返回的列、定义查询条件等。这种灵活性使得动态SQL非常适用于那些需要根据用户输入或其他条件来构建查询的场景。
驼峰映射(Camel Case Mapping)和resultMap是在ORM(对象关系映射)中常用的两种映射方式,用于将数据库查询结果映射到对象模型中的属性。
驼峰映射:
驼峰映射是一种命名约定,将数据库表的列名转换为对象的属性名。具体来说,它将使用小写字母分隔的数据库列名(例如: first_name)转换为驼峰命名法(Camel Case)的对象属性名(例如: firstName)。
在使用驼峰映射时,ORM框架会自动执行列名与对象属性名之间的转换,不需要额外的配置。这种映射方式简化了查询结果到对象属性之间的转换过程。
resultMap:
resultMap是一种显示映射配置方式,将查询结果的列映射到对象的属性。通过定义resultMap,你可以灵活地指定数据库列和对象属性之间的映射关系。
在resultMap中,你可以指定每个属性的映射方式,包括列名、属性名、数据类型转换、关联关系等。你可以根据需要,灵活地配置和定制映射规则。使用resultMap相对于驼峰映射,能够更加精确地控制映射规则的处理,尤其适用于复杂的映射需求。
总之:
驼峰映射是一种命名约定,将数据库表的列名转换为对象的属性名,它是ORM框架提供的默认映射方式。而resultMap是一种显示的映射配置方式,能够更加精确地控制查询结果到对象属性的映射规则,适用于复杂的映射需求。根据具体的使用场景和需求,你可以选择使用驼峰映射或者resultMap来实现映射操作。