Solve the inconsistency between database field names and class member variable names: as, resultMap

The variable name in the entity class is inconsistent with the variable name of the database corresponding table. If no alias is added in the sql, the corresponding field will not be found, and a null pointer exception will be reported. If the entity class is the same as the database field, there is no need to add As

Method 1: SQL statement uses as
Method 2: Mybatis uses resultMap

Case:

Database table:
Insert picture description here
class company member variables:
Insert picture description here

When the database field name is inconsistent with the member variable name of our class, there are two main ways to achieve the mapping:

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

The original: select * from ss_company
changed:

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标签进行数据库列与类的成员变量的映射

The resultMap tag maps the database and entity classes

  • Tag id, corresponding to the primary key of the database table
  • Tag result, corresponding to other columns of the database that are not primary keys ( 把名不一样的改即可)
  • The attribute column corresponds to the column name of the database table, and the attribute property corresponds to the entity class

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>

Guess you like

Origin blog.csdn.net/qq_41209886/article/details/109254754