实体类驼峰命名导致查询出现null

发布时间 2023-03-25 11:16:52作者: YE-

出现的问题:

运行测试类的时候,brandName,companyName出现null值

 原因:数据库表的字段名  和  实体类的属性名称 不一样,则不能自动封装数据

navicat命名方式:

实体类代码

private String brandName;
private String companyName;

select查询语句代码:

<select id="selectAll" resultType="com.Ye.pojo.Brand">
            select *from tb_brand;
        </select>

解决方法:

方法一:

* 起别名:对不一样的列名起别名,让别名和实体类属性名一样
<select id="selectAll" resultType="com.Ye.pojo.Brand">
            select id, brand_name as brandName, company_name as companyName,  ordered, description, status
            from tb_brand;
        </select>

     Ps.不灵活,需要手动输入各种类名和别名,每次查询都需要定义别名

        Ps.解决方法:使用sql片段,但是还是不灵活

<!--    **sql片段    -->
    <sql id="brand_colum">
        id, brand_name as brandName, company_name as companyName, ordered, description, status
    </sql>

        <select id="selectAll" resultType="com.Ye.pojo.Brand">
            select <include refid="brand_colum"></include>
            from tb_brand;
        </select>

方法二:

  <!--
       **数据库表的字段名 和 实体类的属性名称 不一样,则不能自动封装数据
                * 起别名:对不一样的列名起别名,让别名和实体类属性名一样
                        *每次查询都需要定义别名 使用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>