Two solutions to solve the inconsistency of entity class attributes and column names
The first type (fast execution efficiency, low development efficiency)
- The attributes in the class are id, name, password
- The fields in the database are user_id, user_name, user_password
- In order to allow the data queried by the database to be encapsulated in the User object, aliases can be used
. This should be written in the mapping file.
<select id="findAll" resultType="com.yixuexi.entity.User">
select user_id as id,user_name as name,user_password as password from user;
</select>
Summary: This solution is relatively primitive. If there are more fields in the table, the development speed will be very slow.
The second solution (low execution efficiency, fast development speed)
- Use a configuration of mybatis
- Configure this directly in the mapping file
<!--id 就是起个名,在使用的时候用这个名就行 type 是哪个实体类-->
<resultMap id="userMap" type="com.yixuexi.entity.User">
<!--id 是配置主键字段的对应 property 写类中的属性名 column写数据库中对应的字段名-->
<id property="id" column="user_id"></id>
<!--result 是非主键字段的对应-->
<result property="name" column="user_name"></result>
<result property="password" column="user_password"></result>
</resultMap>
- Do not use resultType to indicate the result type when querying, use resultMap
<select id="findAll" resultMap="userMap">
select user_id,user_name,user_password from user
</select>
This can be queried and encapsulated in the entity class.
Notes
- Do not use resultType but use the id of resultMap
- The subtag id in resultMap is used to configure the primary key field
- The subtag result in resultMap is used to configure non-primary key fields
Next article update: JDBC.properties referenced in the main configuration file and some tags of the main configuration file