Getting mybatis --day02: If the column name and the database is inconsistent entity class how to solve?

1. Question: If the column name and the entity class database inconsistency (two solutions)

The name of the entity class member variables are:

    private Integer userId;
    private String userName;
    private Date userBirthday;
    private String userSex;
    private String userAddress;

Column named database:
Here Insert Picture Description

2. Solution one: surnamed

Surnamed by id as userId method to solve. May be modified as follows after the normal operation.

    <select id="findAll" resultType="com.itheima.domain.User">
        <!--select * from user-->
        select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user
    </select>

3. Solution two: Configure the correspondence between the entity class attribute names and column names of the query results

IUserDao.xml configured to:

    <!--配置实体类属性名和查询结果列名的对应关系-->
    <resultMap id="userMap" type="com.itheima.domain.User">
        <!--主键字段的对应-->
        <id property="userId" column="id"/>
        <!--非主键字段的对应-->
        <result property="userName" column="username"/>
        <result property="userAddress" column="address"/>
        <result property="userSex" column="sex"/>
        <result property="userBirthday" column="birthday"/>
    </resultMap>

    <!--配置查询所有-->
    <!--resultType表示要封装到哪里去-->
    <select id="findAll" resultMap="userMap">
        select * from user
        <!--select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user-->
    </select>

Note here: To change resultType resultMap = "userMap", specify encapsulation resultMap the results achieved mapping data. This process requires a period of more than parse xml, so there is no way a high efficiency, but can improve the development efficiency: because the back findById and findByName only need to modify resultType.

Guess you like

Origin blog.csdn.net/dl674756321/article/details/90675795