[MyBatis] | MyBatis query statement topic (the return value type column of the method in the interface)

Table of contents

One: MyBatis query statement topic

1. Return the Car object

2. Return List<Car>

3. Return to Map

4. Return List<Map>

5. return Map<String,Map>

6. resultMap result mapping

7. Return the total number of records


One: MyBatis query statement topic

Early preparation:

Module name: mybatis-008-select

Packaging method: jar

Import dependencies: mysql driver dependencies, mybatis dependencies, logback dependencies, and junit dependencies.

Import configuration files: jdbc.properties, mybatis-config.xml, logback.xml

Create pojo class: com.bjpowernode.mybatis.pojo.Car

Create Mapper interface: com.bjpowernode.mybatis.mapper.CarMapper

Create a mapping file corresponding to the Mapper interface: com/powernode/mybatis/mapper/CarMapper.xml

Create a unit test: com.bjpowernode.mybatis.test.CarMapperTest

Copy tool class: com.bjpowernode.mybatis.utils.SqlSessionUtils 

1. Return the Car object

Query results, the returned object is a Car object!

One of the three brothers: CarMapper interface, write method

Define an abstract method in the interface, query by id, and return a Car object

package com.bjpowernode.mybatis.mapper;

import com.bjpowernode.mybatis.pojo.Car;

public interface CarMapper {
    // 根据id进行查询,返回的是Car
    Car selectById(Long id);
}

The second of three brothers: CarMapper.xml file, write sql statement

The namespace specified must be the package name of the interface, and the id of select must be the method name of the method!

②select * from t_car where id = #{id}; There will definitely be problems with this query. I have already touched it before. Except for the id and brand fields, other fields are empty; because the field names in the database table are different from the field names of the Car object. same!

③How to solve it?

Use as to rename the field, or use the name attribute of the settings tag to set mapUnderscoreToCamelCase, and set the value to true to enable the hump naming rule!

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectById" resultType="Car">
        <!--select * from  t_car where id = #{id};-->
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from  t_car where id = #{id};
    </select>
</mapper>

The third of three brothers: CarMappeTest class, used to write test classes

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class CarMapperTest {
    @Test
    public void testSelectById(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = mapper.selectById(1L);
        System.out.println(car);
        sqlSession.close();
    }
}

2. Return List<Car>

In the query result, the returned objects are multiple Car objects, which requires a List collection for storage!

One of the three brothers: CarMapper interface, write method

Define an abstract method in the interface, query all Cars, return multiple Car objects, and use the List collection to receive.

Note: or perform fuzzy query, multiple Car objects are also returned.

Note: If you know that multiple objects are returned, but use a POJO class Car to receive them, a TooManyResultsException will be reported: indicating that the expected result is to return a piece of data, but when the actual SQL statement is executed, the returned record is not One or more.

Note: If you know that the returned data is a Car object, but we use a List collection to receive it, this is no problem

package com.bjpowernode.mybatis.mapper;

import com.bjpowernode.mybatis.pojo.Car;

public interface CarMapper {
    // 获取所有的Car,返回一个List集合
    List<Car> selectAll();
}

The second of three brothers: CarMapper.xml file, write sql statement

There is no where query condition, and the query is the results in all database tables

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectById" resultType="Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from  t_car;
    </select>
</mapper>

The third of three brothers: CarMappeTest class, used to write test classes

Query all, return a List collection, just traverse this collection and print

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class CarMapperTest {
    @Test
    public void testSelectAll(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> cars = mapper.selectAll();
        cars.forEach(car -> System.out.println(car));
        sqlSession.close();
    }
}

3. Return to Map

(1) When the returned data does not correspond to a suitable entity class, it can be received by a Map collection; the field name in the database is used as the key, and the field value in the database is used as the value.

(2) If the query can guarantee that there is only one piece of data, then return a Map collection. For example:

One of the three brothers: CarMapper interface, write method

Query based on id returns a Map collection, the key of the Map collection must be a String type; the value of the Map collection must be an Object, because the specific types are different.

package com.bjpowernode.mybatis.mapper;

public interface CarMapper {
    // 根据id返回汽车信息,将汽车信息放到Map集合
    Map<String, Object> selectByIdReturnMap(Long id);
}

The second of three brothers: CarMapper.xml file, write sql statement

Note: Here is mainly how to write the value of the resultType attribute?

Use the Map collection to receive, so use: java.util.Map, of course, you can also use the built-in alias map of MyBatis.

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectByIdReturnMap" resultType="map">
        select *  from  t_car where id = #{id};
    </select>
</mapper>

The third of three brothers: CarMappeTest class, used to write test classes

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class CarMapperTest {
    @Test
    public void testSelectByIdReturnMap(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Map<String, Object> map = mapper.selectByIdReturnMap(1L);
        System.out.println(map);
        sqlSession.close();
    }
}

Results of the:

 

4. Return List<Map>

If the returned data does not correspond to a suitable entity class, and the number of query results is greater than or equal to 1 piece of data, you can return a List collection that stores the Map collection: List<Map>, which is actually equivalent to List<Car> .

 One of the three brothers: CarMapper interface, write method

The above is that the query returns a result, which can be received by using the Map collection; now it is querying all, and what is returned is a List collection that stores the Map collection.

package com.bjpowernode.mybatis.mapper;

public interface CarMapper {
    // 查询所有的Car信息,返回的是一个存放Map集合的List集合
    List<Map<String,Object>> selectAllReturnListMap();
}

The second of three brothers: CarMapper.xml file, write sql statement

Note: Here is mainly the value of the resultType attribute or fill in the element Map collection in the List collection

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectAllReturnListMap" resultType="map">
        select *  from  t_car;
    </select>
</mapper>

The third of three brothers: CarMappeTest class, used to write test classes

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class CarMapperTest {
    @Test
    public void testSelectAllReturnListMap(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Map<String, Object>> maps = mapper.selectAllReturnListMap();
        maps.forEach(map-> System.out.println(map));
        sqlSession.close();
    }
}

5. return Map<String,Map>

When returning List<Map>, it is not easy to fetch data. If you fetch the element whose id is 3, you need to traverse the entire collection; so we can return a large Map collection: Map<String, Map>; take the id of Car It is more convenient to take out the corresponding Map collection in the future when it is used as the key and the Map collection as the value.

 One of the three brothers: CarMapper interface, write method

① In the above method, if you take out a certain data, you need to traverse the entire collection, so we use another way to store:

Take the id of the Car as the key, the Map collection as the value, and put it in a large Map collection!

②Using this method requires an annotation: @MapKey("id"), indicating that the id of each data query result is used as the key of the entire large Map collection

package com.bjpowernode.mybatis.mapper;

public interface CarMapper {
    // 查询所有的Car,返回一个大Map集合
    @MapKey("id") 
    Map<Long,Map<String,Object>> selectAllReturnMapMap();
}

The second of three brothers: CarMapper.xml file, write sql statement

Note: The value of the resultType attribute here is still to fill in the small Map collection of elements in the large Map collection

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectAllReturnMapMap" resultType="map">
        select *  from  t_car;
    </select>
</mapper>

The third of three brothers: CarMappeTest class, used to write test classes

Note: The fetched data is to query all the data and put them into a large Map collection

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class CarMapperTest {
    @Test
    @Test
    public void testSelectAllReturnMapMap(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Map<Long, Map<String, Object>> doubleMap = mapper.selectAllReturnMapMap();
        System.out.println(doubleMap);
        sqlSession.close();
    }
}

Results of the:

6. resultMap result mapping

What should I do if the column name of the query result does not correspond to the attribute name of the java object?

① The first method: as to give an alias to the column, the method that has been used before.

②The second method: use resultMap for result mapping.

③The third method: whether to enable the automatic mapping of hump naming. 

(1) Use resultMap for result mapping

 One of the three brothers: CarMapper interface, write method

package com.bjpowernode.mybatis.mapper;

import com.bjpowernode.mybatis.pojo.Car;
import org.apache.ibatis.annotations.MapKey;
import java.util.*;

public interface CarMapper {
    // 查询所有的Car信息,使用resultMap标签进行结果映射
    List<Car> selectAllByResultMap(); 
}

The second of three brothers: CarMapper.xml file, write sql statement

①The previous method uses as to rename, and each field needs to be written out, which is troublesome.

② Now define a result mapping specifically, specify the corresponding relationship between the field name of the database table and the attribute name of the Java class in this result mapping.

③Result mapping resultMap has two parameters:

One parameter is id, which specifies the unique identifier of the resultMap. This id will be used in the resultMap attribute in the select tag in the future (note: it is no longer the resultType attribute).

One parameter is type, which is used to specify the class name of the POJO class.

There is also a sub-label result under resultMap:

First of all, it is not necessary to use an id tag for those with a primary key, but it can increase efficiency.

Then use the property attribute and column attribute of the result sub-tag to specify the mapping relationship between the attribute name of the POJO class and the field table in the database table.

⑤ You can also configure javaType and jdbcType attributes for the current tag, which is not necessary, but it can increase efficiency because MyBatis automatically infers less.

⑥The select tag uses the resultMap attribute, and the original resultType attribute does not need to be specified.

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <!--这里的car就是com.bjpowernode.mybatis.pojo.Car,使用了内置的别名-->
    <resultMap id="CarResultMap" type="car">
        <!--数据库表中有主键,建议配一个id,可以提高效率-->
        <id property="id" column="id" />

        <!--property后面填写POJO类的属性名,column后面填写数据库表中的字段名-->
        <result property="carNum" column="car_num" />
        <!--如果property和column是一样的,可以省略-->
        <!-- <result property="brand" column="brand" />-->
        <result property="guidePrice" column="guide_price" />
        <result property="produceTime" column="produce_time" />
        <!--当然也可以指定javaType和jdbcType属性,减少自动推断,效率可能更高-->
        <result property="carType" column="car_type" javaType="string" jdbcType="VARCHAR" />
    </resultMap>
    <!--select标签的resultMap属性用来指定使用哪个结果映射,后面跟的是resultMap的id-->
    <select id="selectAllByResultMap" resultMap="CarResultMap">
        select * from t_car;
    </select>
</mapper>

The third of three brothers: CarMappeTest class, used to write test classes

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class CarMapperTest {
    @Test
    public void testSelectAllByResultMap(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> cars = mapper.selectAllByResultMap();
        cars.forEach(car -> System.out.println(car));
        sqlSession.close();
    }
}

(2) Whether to enable automatic mapping of hump naming (configuration settings)

Premise: The attribute name follows the naming convention of Java, and the column name of the database table follows the naming convention of SQL.

①Java naming convention: the first letter is lowercase, and the first letter of each subsequent word is uppercase, following the hump naming method.

②SQL naming convention: all lowercase, words are separated by underscores.

For example, the following correspondences:

How to enable this function, configure it in the core configuration file mybatis-config.xml:

<!--放在properties标签后⾯-->
<settings>
 <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

 One of the three brothers: CarMapper interface, write method

package com.bjpowernode.mybatis.mapper;

import com.bjpowernode.mybatis.pojo.Car;
import org.apache.ibatis.annotations.MapKey;
import java.util.*;

public interface CarMapper {
    // 查询所有Car,启⽤驼峰命名⾃动映射
    List<Car> selectAllByMapUnderscoreToCamelCase();
}

The second of three brothers: CarMapper.xml file, write sql statement

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectAllByMapUnderscoreToCamelCase" resultType="car">
        select * from t_car;
    </select>
</mapper>

 The third of three brothers: CarMappeTest class, used to write test classes

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class CarMapperTest {
    @Test
    public void testSelectAllByMapUnderscoreToCamelCase(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> cars = mapper.selectAllByMapUnderscoreToCamelCase();
        cars.forEach(car -> System.out.println(car));
        sqlSession.close();
    }
}

7. Return the total number of records

Requirements: Query the total number of records, use the count function!

  One of the three brothers: CarMapper interface, write method

The return type of the method can be defined as Long or Integer, and Long is used here

package com.bjpowernode.mybatis.mapper;

import com.bjpowernode.mybatis.pojo.Car;
import org.apache.ibatis.annotations.MapKey;
import java.util.*;

public interface CarMapper {
    // 获取总记录条数
    Long selectTotal();
}

The second of three brothers: CarMapper.xml file, write sql statement

Note: The type we returned earlier is Long, so the specified type of resultType here is also long (alias)

<?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.bjpowernode.mybatis.mapper.CarMapper">
    <select id="selectTotal" resultType="long">
        select count(*) from t_car;
    </select>
</mapper>

 The third of three brothers: CarMappeTest class, used to write test classes

package com.bjpowernode.mybatis.test;

import com.bjpowernode.mybatis.mapper.CarMapper;
import com.bjpowernode.mybatis.pojo.Car;
import com.bjpowernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;
import java.util.Map;

public class CarMapperTest {
   @Test
    public void testSelectTotal(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Long total = mapper.selectTotal();
        System.out.println("总记录条数"+total);
        sqlSession.close();
    }
}

Guess you like

Origin blog.csdn.net/m0_61933976/article/details/128563890