实体类属性和数据库列名不一致,不能自动封装数据 ,查出的数据就是null
解决方案
1 起别名:
在sql语句中,对不一样的列名起别名,别名和实体类的属性名一样
<select id="selectAll" resultType="Brand">
SELECT id,brand_name as brandName, company_name as companyName, ordered, description, status FROM tb_brand
</select>
还可以使用<sql>片段提高复用性
定义sql片段
<sql id="brand_column">id,brand_name as brandName, company_name as companyName, ordered, description, status</sql>
在查询即可
<select id="selectAll" resultType="Brand">
select *
from tb_brand;
</select>
2:resultMap
定义<resultMap>完成不一致的属性名和列名的映射
步骤 :1 定义<resultMap>标签
<resultMap id="BrandresultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
2 在<select> 标签中使用resultMap属性替换resultType属性
<select id="selectAll" resultMap="BrandresultMap">
select * from tb_brand;
</select>
resultMap id: 唯一标识
type: 映射类型可以是别名的形式
result:映射一般的字段
id:映射主键 不一样的才会采用映射
column:数据库字段名 property:实体字段名
补充一下:我的<resultMap>标签 直接用的别名是因为在配置文件中更改了。
类型别名 在映射配置文件中的 resultType 属性需要配置数据封装的类型(类的全限定名)。而每次这样写是特别麻烦的,Mybatis 提供了 类型别名 (typeAliases) 可以简化这部分的书写。 首先需要现在核心配置文件中配置类型别名,也就意味着给pojo包下所有的类起了别名(别名就是类名),不区分大小写。 内容如下:
<typeAliases>
<!--name属性的值是实体类所在包-->
<package name="com.chen.pojo"/>
</typeAliases>
要按这个层级顺序
通过上述的配置,我们就可以简化映射配置文件中 resultType 属性值的编写