11 数据库表中列与实体类属性不一致的处理方式
张创琦 2022.03.13
- 创建 sql 表
use ssm1;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`user_id` int NOT NULL AUTO_INCREMENT COMMENT '用户id',
`user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户姓名',
`user_age` int NULL DEFAULT NULL COMMENT '用户年龄', PRIMARY KEY (`user_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
INSERT INTO `users` VALUES (1, '贾宝玉', 14); INSERT INTO `users` VALUES (2, '林黛玉', 13); INSERT INTO `users` VALUES (3, '薛宝钗', 15);
SET FOREIGN_KEY_CHECKS = 1;
- 创建实体类
package com.kkb.pojo;
public class Users {
private Integer userId;
private String userName;
private Integer userAge;
@Override
public String toString() {
return "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAge=" + userAge +
'}';
}
// 省略 getter 和 setter 方法
}
- 编写 UsersMapper.java 接口类
package com.kkb.mapper;
import com.kkb.pojo.Users;
public interface UsersMapper {
// 1 使用列别名和resultType
Users queryByID(int userId);
// 2 使用resultMap
Users queryByID2(int userId);
}
- 编写UsersMapper.xml 配置文件
路径在:com.kkb.test 下面
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kkb.mapper.UsersMapper">
<!--方式1:resultType中的实体类的属性作为查询语句中的别名,让别名和属性保持一致-->
<select id="queryByID" resultType="com.kkb.pojo.Users">
select user_id as userId,user_name as userName,user_age as userAge from users where user_id=#{id};
</select>
<!--方式2:通过resultMap自行映射-->
<select id="queryByID2" resultMap="baseMap">
select * from users where user_id=#{id};
</select>
<resultMap id="baseMap" type="com.kkb.pojo.Users">
<id column="user_id" property="userId"/>
<result column="user_name" property="userName"/>
<result column="user_age" property="userAge"/>
</resultMap>
</mapper>
- 在 mybatis.xml 中配置文件映射地址
<!-- 注册映射文件 -->
<mappers>
<!-- 之前注册过的 -->
<mapper resource="com/kkb/mapper/UsersMapper.xml"></mapper>
</mappers>
- 编写测试类
package com.kkb.test;
import com.kkb.mapper.UsersMapper;
import com.kkb.pojo.Users;
import com.kkb.utils.MybatisUtil;
import org.apache.ibatis.annotations.Mapper;
import org.junit.Test;
public class TestUsersMapper {
private UsersMapper usersMapper= MybatisUtil.getSqlSession().getMapper(UsersMapper.class);
// 测试成功
@Test
public void test01(){
Users user = usersMapper.queryByID(1);
System.out.println(user);
}
// 测试成功
@Test
public void test02(){
Users user = usersMapper.queryByID2(1);
System.out.println(user);
}
}