解决数据库字段名与类的成员变量名不一致:as、resultMap

实体类中的变量与数据库对应表的变量名不一致,如果sql 中没有添加别名, 那么会找不到对应的字段, 则会报空指针异常。如果实体类和数据库字段一样则不需要加As

方法1:sql语句 使用 as
方法2:mybatis里面使用 resultMap

案例:

数据库表:
在这里插入图片描述
类company成员变量:
在这里插入图片描述

当数据库的字段名和我们的类的成员变量名不一致,主要通过两种方法实现映射:

1、通过sql语句,使用 as 起别名

原来:select * from ss_company
改后:

companyDao.xml

<select id="findAll" resultType="company">
select
	id,
	name ,
	expiration_date as expirationDate ,
	address,
	license_id as licenseId  ,
	representative ,
	phone  ,
	company_size as companySize  ,
	industry  ,
	remarks ,
	state,
	balance ,
	city
from ss_company
    </select>

2、通过resultMap标签进行数据库列与类的成员变量的映射

resultMap标签进行数据库与实体类的映射

  • 标签id,对应数据库表的主键
  • 标签result,对应数据库非主键的其他列(把名不一样的改即可
  • 属性column对应数据库表的列名,属性property对应实体类

companyDao.xml

<resultMap id="companyMap" type="company">
        <id column="id" property="id"/>
        <result column="expiration_date" property="expirationDate"/>
        <result column="license_id" property="licenseId"/>
        <result column="company_size" property="companySize"/>
    </resultMap>
    <select id="findAll" resultMap="companyMap">
        select * from ss_company
    </select>

猜你喜欢

转载自blog.csdn.net/qq_41209886/article/details/109254754