11 数据库表中列与实体类属性不一致的处理方式

张创琦 2022.03.13

  1. 创建 sql 表
  1. use ssm1;
  2. DROP TABLE IF EXISTS `users`;
  3. CREATE TABLE `users` (
  4. `user_id` int NOT NULL AUTO_INCREMENT COMMENT '用户id',
  5. `user_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户姓名',
  6. `user_age` int NULL DEFAULT NULL COMMENT '用户年龄', PRIMARY KEY (`user_id`) USING BTREE
  7. ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
  8. INSERT INTO `users` VALUES (1, '贾宝玉', 14); INSERT INTO `users` VALUES (2, '林黛玉', 13); INSERT INTO `users` VALUES (3, '薛宝钗', 15);
  9. SET FOREIGN_KEY_CHECKS = 1;
  1. 创建实体类
  1. package com.kkb.pojo;
  2. public class Users {
  3. private Integer userId;
  4. private String userName;
  5. private Integer userAge;
  6. @Override
  7. public String toString() {
  8. return "Users{" +
  9. "userId=" + userId +
  10. ", userName='" + userName + '\'' +
  11. ", userAge=" + userAge +
  12. '}';
  13. }
  14. // 省略 getter 和 setter 方法
  15. }
  1. 编写 UsersMapper.java 接口类
  1. package com.kkb.mapper;
  2. import com.kkb.pojo.Users;
  3. public interface UsersMapper {
  4. // 1 使用列别名和resultType
  5. Users queryByID(int userId);
  6. // 2 使用resultMap
  7. Users queryByID2(int userId);
  8. }
  1. 编写UsersMapper.xml 配置文件

路径在:com.kkb.test 下面

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.kkb.mapper.UsersMapper">
  5. <!--方式1:resultType中的实体类的属性作为查询语句中的别名,让别名和属性保持一致-->
  6. <select id="queryByID" resultType="com.kkb.pojo.Users">
  7. select user_id as userId,user_name as userName,user_age as userAge from users where user_id=#{id};
  8. </select>
  9. <!--方式2:通过resultMap自行映射-->
  10. <select id="queryByID2" resultMap="baseMap">
  11. select * from users where user_id=#{id};
  12. </select>
  13. <resultMap id="baseMap" type="com.kkb.pojo.Users">
  14. <id column="user_id" property="userId"/>
  15. <result column="user_name" property="userName"/>
  16. <result column="user_age" property="userAge"/>
  17. </resultMap>
  18. </mapper>
  1. 在 mybatis.xml 中配置文件映射地址
  1. <!-- 注册映射文件 -->
  2. <mappers>
  3. <!-- 之前注册过的 -->
  4. <mapper resource="com/kkb/mapper/UsersMapper.xml"></mapper>
  5. </mappers>
  1. 编写测试类
  1. package com.kkb.test;
  2. import com.kkb.mapper.UsersMapper;
  3. import com.kkb.pojo.Users;
  4. import com.kkb.utils.MybatisUtil;
  5. import org.apache.ibatis.annotations.Mapper;
  6. import org.junit.Test;
  7. public class TestUsersMapper {
  8. private UsersMapper usersMapper= MybatisUtil.getSqlSession().getMapper(UsersMapper.class);
  9. // 测试成功
  10. @Test
  11. public void test01(){
  12. Users user = usersMapper.queryByID(1);
  13. System.out.println(user);
  14. }
  15. // 测试成功
  16. @Test
  17. public void test02(){
  18. Users user = usersMapper.queryByID2(1);
  19. System.out.println(user);
  20. }
  21. }