MyBatis learning summary (4) - resolution of conflicts between field names and entity class attribute names

  The field name in the table and the attribute name of the entity class corresponding to the table are not necessarily exactly the same. In this case, how to solve the conflict between the field name and the attribute name of the entity class is not the same. As follows:

1. Prepare the tables and data needed for the presentation

CREATE TABLE my_user(
    user_id INT PRIMARY KEY AUTO_INCREMENT,
    user_no VARCHAR(20),
    user_age int
);
INSERT INTO my_user(user_no , user_age ) VALUES('myl', 15);
INSERT INTO my_user(user_no , user_age ) VALUES('test', 11);

 

Second, define the entity class

package com.myl.entity;

import java.util.Date;

/ ** 
 * @author myl
 *@date April 27, 2018 at 6:35:17 AM
 */

public  class User {
     // The attribute name in the U entity class is different from the field name in the my_user table 
    private  int id;             // id corresponds to user_id 
    private String no;         // no corresponds to user_no 
    private  int age;         // age corresponds to user_age
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getNo() {
        return no;
    }
    public void setNo(String no) {
        this.no = no;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", no=" + no + ", age=" + age + "]";
    }
    
}

 

3. Write test code

3.1, write SQL xml mapping file

  1. Create an orderMapper.xml file. The content of orderMapper.xml is as follows:

<?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">

<!-- 
    Specify a unique namespace for this mapper. The value of the namespace is conventionally set to the package name + sql mapping file name, so that the value of the namespace can be guaranteed to be unique.
      For example, namespace="com.myl.mapping.userMapper" is com.myl.mapping (package name) + userMapper (the userMapper.xml file removes the suffix)
 -->
 
<mapper namespace="com.myl.entity.userMapper">

 <!-- 
     Write the SQL statement of the query in the select tag, set the id attribute of the select tag to getUser, the value of the id attribute must be unique and cannot be repeated
      Use the parameterType attribute to indicate the parameter type used in the query, and the resultType attribute to indicate the result set type returned by the query
    resultType="com.myl.entity.User" means to encapsulate the query result into an object of the User class and return it
    The User class is the entity class corresponding to the users table
  -->      
 
     <!-- Can't get normal results, because the attribute name of the entity class does not correspond to the field name of the database, so the corresponding record cannot be queried --> 
    < select id ="getUserByB" parameterType ="int" resultType =" com.myl.entity.User" >
        select * from my_user where user_id=#{id}
    </select>
    
    <!-- Can't get normal results, because the attribute name of the entity class does not correspond to the field name of the database, so the corresponding record cannot be queried --> 
    < select id = "getAllUserByB" resultType = "com.myl.entity" .User" >
        select * from my_user
    </select>
 
      <!-- Get normal results, get a user object according to id query --> 
    < select id ="getUser" parameterType ="int" resultType ="com.myl.entity.User" >
        select user_id id,user_no no,user_age age from my_user where user_id=#{id}
    </select>
    
    <!-- Get normal results, find all data --> 
    < select id = "getAllUser" resultType = "com.myl.entity.User" >
        select user_id id,user_no no,user_age age from my_user
    </select>
    
    <!-- Get normal results, map the attribute name of the entity class and the field name of the table one-to-one correspondence through <resultMap>   --> 
    < select id = "getUserByResultMap" parameterType = "int" resultMap = "UserResultMap" >
        select * from my_user where user_id=#{id}
    </select>
    
    <!-- Get normal results, map the attribute name of the entity class and the field name of the table one-to-one correspondence through <resultMap>   --> 
    < select id = "getAllUserByResultMap" resultMap = "UserResultMap" >
        select * from my_user
    </select>
    
    <!-- Map the corresponding relationship between the attribute name of the entity class and the field name of the table through <resultMap> --> 
    < resultMap type = "com.myl.entity.User" id = "UserResultMap" > 
        <!-- Use the id attribute to map Primary key field --> 
        < id property = "id" column = "user_id" ></ id > 
         <!-- Use the result attribute to map non-primary key fields --> 
        < result property = "no" column = "user_no" / > 
        < result property = "age" column = "user_age" />
    </resultMap>
 
</mapper>

 

2. Register the userMapper.xml mapping file in the mybatisConf.xml file

    <mappers>
      <!-- 
        Register the userMapper.xml file,
         userMapper.xml is located under the package me.myl.mapping, so the resource is written as me/myl/mapping/userMapper.xml
        -->
        <mapper resource="com/myl/mapping/userMapper.xml"/>

    </mappers>

 

3.2, write unit test code

package com.myl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.myl.entity.User;
import com.myl.util.MybatisUtil;
/**
 * Test CRUD
 * @author myl
 *@date April 27, 2018 at 6:29:42 AM
 */ 
public  class TestCRUD {
    
    @Test
    public  void getUserByIdByB() {
        SqlSession sqlSession = MybatisUtil.getSession();
        /**
         * Execute the operation, getUser is the value of the id attribute of the select
         */
        User user = sqlSession.selectOne("getUserByB", 1);
        System.out.println(user);
        // After using sqlSession to execute sql, close sqlSession 
        sqlSession.close();     // Print result: null, that is, no corresponding record is queried 
    }
    
    @Test
    public  void getAllUserByB () {
        SqlSession sqlSession = MybatisUtil.getSession();
        /**
         * Execute the query operation, and automatically encapsulate the query result into a List<User> and return it
         * getAllUserByB is the value of the id attribute of the select tag
         */
        List<User> userList = sqlSession.selectList("getAllUserByB");
        
        for(User user : userList){
            System.out.println(user);
        }
        sqlSession.close();     // Print result: null null null means no corresponding record is queried 
    }

    @Test
    public  void getUserById() {
        SqlSession sqlSession = MybatisUtil.getSession();
        /**
         * Execute the operation, getUser is the value of the id attribute of the select
         */
        User user = sqlSession.selectOne("getUser", 1);
        System.out.println(user);     // Print result: User [id=1, no=myl, age=22]
         // After using sqlSession to execute sql, close sqlSession 
        sqlSession.close();    
    }
    
    @Test
    public  void getAllUser () {
        SqlSession sqlSession = MybatisUtil.getSession();
        /**
         * Execute the query operation, and automatically encapsulate the query result into a List<User> and return it
         * getAllUser is the value of the id attribute of the select tag
         */
        List<User> userList = sqlSession.selectList("getAllUser");
        
        for(User user : userList){
            System.out.println(user);     // Print result: User [id=1, no=myl, age=22] multiple 
        }
        sqlSession.close();
    }
    
    @Test
    public void getUserByIdByResultMap() {
        SqlSession sqlSession = MybatisUtil.getSession();
        /**
         * Execute the operation, getUser is the value of the id attribute of the select
         */
        User user = sqlSession.selectOne("getUserByResultMap", 1);
        System.out.println(user);     // Print result: User [id=1, no=myl, age=22]
         // After using sqlSession to execute sql, close sqlSession 
        sqlSession.close();
    }
    
    @Test
    public  void getAllUserResultMap () {
        SqlSession sqlSession = MybatisUtil.getSession();
        /**
         * Execute the query operation, and automatically encapsulate the query result into a List<User> and return it
         * getAllUser is the value of the id attribute of the select tag
         */
        List<User> userList = sqlSession.selectList("getAllUserByResultMap");
        
        for(User user : userList){
            System.out.println(user);     // Print result: User [id=1, no=myl, age=22] multiple 
        }
        sqlSession.close();
    }

}

 

Test Results:

  getUserByIdByB null (error)

  getAllUserByB multiple nulls (error)

  getUserById User [id=1, no=myl, age=22] (correct)

  getAllUser User [id=1, no=myl, age=22] multiple (correct)

  getUserByIdByResultMap User [id=1, no=myl, age=22] (correct)

  getAllUserResultMap User [id=1, no=myl, age=22] multiple (correct)

4. Summary

  The test code demonstrates the problem that when the attribute name in the entity class is inconsistent with the field name in the table, the corresponding result cannot be queried when using MyBatis for query operation, and two methods are adopted for the problem:

  Method 1 By defining the alias of the field name in the sql statement of the query, make the alias of the field name consistent with the attribute name of the entity class, so that the field name of the table and the attribute name of the entity class can be in one-to-one correspondence, this way The mapping relationship between field names and attribute names is resolved by defining aliases in SQL statements.

  Method 2 Use <resultMap> to map the one-to-one correspondence between field names and entity class attribute names. This method uses the solution provided by MyBatis to solve the mapping relationship between field names and attribute names.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324916742&siteId=291194637