MyBatis案例:查询所有数据
MyBatis案例:查询所有数据
- 编写接口方法:Mapper接口
- 参数:无
- 结果:
List<Brand>
- 编写SQL语句:SQL映射文件
- 执行方法,测试
结果映射:
实体类属性名和数据库表列名不一致,不能自动封装数据,有以下两种解决方法
- 起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样,可以定义
<sql>
片段,提升复用性 - resultMap: 定义
<resultMap>
完成不一致的属性名和列名的映射
<!--BrandMapper.xml文件部分内容-->
<mapper namespace="com.charley.mapper.BrandMapper">
<!--
数据库表的字段名称 和 实体类的属性名称 不一样,则不能自动封装数据
* 起别名: 对不一样的列名起别名,让别名和实体类的属性名一样
* 缺点:每次查询都要定义一次别名
* sql片段解决
* 缺点:不灵活
* resultMap:
1. 定义<resultMap>标签
2. 在<select>标签中,使用resultMap属性替换 resultType属性
-->
<!--
id: 唯一标识
type: 映射的类型,支持别名
-->
<resultMap id="brandResultMap" type="brand">
<!--
id: 完成主键字段的映射
column: 表的列名
property: 实体类的属性名
result: 完成一般字段的映射
column: 表的列名
property: 实体类的属性名
-->
<result column="brand_name" property="brandName"/>
<result column="company_name" property="companyName"/>
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
<!--
sql片段
-->
<!--<sql id = "brand_column">
id, brand_name as brandName, company_name as companyName, ordered, description, status
</sql>
<select id="selectAll" resultType="brand">
select
<include refid="brand_column"></include>
from tb_brand;
</select>-->
<!--<select id="selectAll" resultType="brand">
select * from tb_brand;
</select>-->
</mapper>