Mybatis查询结果集返回信息处理之多个Map和单个Map-----Mybatis框架

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.powernode</groupId>
    <artifactId>Mybatis-008-select</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.powernode</groupId>
    <artifactId>Mybatis-008-select</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:13306/powernode
jdbc.username=root
jdbc.password=abc123
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:13306/powernode
jdbc.username=root
jdbc.password=abc123

<?xml version="1.0" encoding="UTF-8" ?>

<configuration debug="false">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.apache.ibatis" level="TRACE">

    </logger>
    <logger name="java.sql.Connection" level="DEBUG">

    </logger>
    <logger name="java.sql.Statement" level="DEBUG">

    </logger>
    <logger name="java.sql.PreparedStatement" level="DEBUG">

    </logger>
    <!--日志级别,由低到高-->
    <!--ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF-->
    <root level="DEBUG">
        <appender-ref ref="STDOUT">

        </appender-ref>
        <appender-ref ref="FILE">

        </appender-ref>
    </root>

</configuration>
<?xml version="1.0" encoding="UTF-8" ?>

<configuration debug="false">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.apache.ibatis" level="TRACE">

    </logger>
    <logger name="java.sql.Connection" level="DEBUG">

    </logger>
    <logger name="java.sql.Statement" level="DEBUG">

    </logger>
    <logger name="java.sql.PreparedStatement" level="DEBUG">

    </logger>
    <!--日志级别,由低到高-->
    <!--ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF-->
    <root level="DEBUG">
        <appender-ref ref="STDOUT">

        </appender-ref>
        <appender-ref ref="FILE">

        </appender-ref>
    </root>

</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>
    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>
    <typeAliases>
        <package name="com.powernode.mybatis.POJO"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.powernode.mybatis.mappers"/>
    </mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>
    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>
    <typeAliases>
        <package name="com.powernode.mybatis.POJO"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.powernode.mybatis.mappers"/>
    </mappers>
</configuration>
<?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.powernode.mybatis.mappers.CarMapper">
    <select id="selectById" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id};
    </select>
    <select id="selectAll" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
    </select>
    <select id="selectByBrand" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            brand like '%${brand}%';
    </select>
    <select id="selectByCarId" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id};
    </select>
<!--    查询结果没有合适的接收对象,没有合适的POJO类-->
    <select id="selectByIdGetMap" resultType="java.util.Map">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id};
    </select>
    <select id="selectAllCar" resultType="Map">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
    </select>
</mapper>
<?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.powernode.mybatis.mappers.CarMapper">
    <select id="selectById" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id};
    </select>
    <select id="selectAll" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
    </select>
    <select id="selectByBrand" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            brand like '%${brand}%';
    </select>
    <select id="selectByCarId" resultType="Car">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id};
    </select>
<!--    查询结果没有合适的接收对象,没有合适的POJO类-->
    <select id="selectByIdGetMap" resultType="java.util.Map">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id};
    </select>
    <select id="selectAllCar" resultType="Map">
        select
            id as id,
            car_num as carNum,
            brand as brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
    </select>
</mapper>
package com.powernode.mybatis.mappers;

import com.powernode.mybatis.POJO.Car;

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

public interface CarMapper
{
    List<Map<String,Object>> selectAllCar();
    Map<String,Object> selectByIdGetMap(Long id);
    List<Car> selectByCarId(Long id);
    //模糊查询的对象可能有多个,会出问题吗?
    Car selectByBrand(String brand);
    List<Car> selectAll();
    Car selectById(Long id);
}
package com.powernode.mybatis.mappers;

import com.powernode.mybatis.POJO.Car;

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

public interface CarMapper
{
    List<Map<String,Object>> selectAllCar();
    Map<String,Object> selectByIdGetMap(Long id);
    List<Car> selectByCarId(Long id);
    //模糊查询的对象可能有多个,会出问题吗?
    Car selectByBrand(String brand);
    List<Car> selectAll();
    Car selectById(Long id);
}
package com.powernode.mybatis.POJO;

public class Car
{
    //这是一个封装汽车相关信息的普通的java类,数据库表中的字段应该和属性一一对应
    //为什么使用包装类,因为当我们查值的时候,返回值有可能是null
    //避免数据不兼容
    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;
    public Car(){};

    public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
        this.id = id;
        this.carNum = carNum;
        this.brand = brand;
        this.guidePrice = guidePrice;
        this.produceTime = produceTime;
        this.carType = carType;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCarNum() {
        return carNum;
    }

    public void setCarNum(String carNum) {
        this.carNum = carNum;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getGuidePrice() {
        return guidePrice;
    }

    public void setGuidePrice(Double guidePrice) {
        this.guidePrice = guidePrice;
    }

    public String getProduceTime() {
        return produceTime;
    }

    public void setProduceTime(String produceTime) {
        this.produceTime = produceTime;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", carNum='" + carNum + '\'' +
                ", brand='" + brand + '\'' +
                ", guidePrice=" + guidePrice +
                ", produceTime='" + produceTime + '\'' +
                ", carType='" + carType + '\'' +
                '}';
    }
}
package com.powernode.mybatis.POJO;

public class Car
{
    //这是一个封装汽车相关信息的普通的java类,数据库表中的字段应该和属性一一对应
    //为什么使用包装类,因为当我们查值的时候,返回值有可能是null
    //避免数据不兼容
    private Long id;
    private String carNum;
    private String brand;
    private Double guidePrice;
    private String produceTime;
    private String carType;
    public Car(){};

    public Car(Long id, String carNum, String brand, Double guidePrice, String produceTime, String carType) {
        this.id = id;
        this.carNum = carNum;
        this.brand = brand;
        this.guidePrice = guidePrice;
        this.produceTime = produceTime;
        this.carType = carType;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCarNum() {
        return carNum;
    }

    public void setCarNum(String carNum) {
        this.carNum = carNum;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Double getGuidePrice() {
        return guidePrice;
    }

    public void setGuidePrice(Double guidePrice) {
        this.guidePrice = guidePrice;
    }

    public String getProduceTime() {
        return produceTime;
    }

    public void setProduceTime(String produceTime) {
        this.produceTime = produceTime;
    }

    public String getCarType() {
        return carType;
    }

    public void setCarType(String carType) {
        this.carType = carType;
    }

    @Override
    public String toString() {
        return "Car{" +
                "id=" + id +
                ", carNum='" + carNum + '\'' +
                ", brand='" + brand + '\'' +
                ", guidePrice=" + guidePrice +
                ", produceTime='" + produceTime + '\'' +
                ", carType='" + carType + '\'' +
                '}';
    }
}
package com.powernode.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class SqlSessionUtil
{
    private SqlSessionUtil(){};
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();
    static
    {
        try
        {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession openSession()
    {
        SqlSession sqlSession = local.get();
        if (sqlSession == null)
        {
            sqlSession = sqlSessionFactory.openSession();
            local.set(sqlSession);
        }
        return sqlSession;
    }
    public static void close(SqlSession sqlSession)
    {
        if(sqlSession != null)
        {
            sqlSession.close();
            local.remove();
        }
    }
}
package com.powernode.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class SqlSessionUtil
{
    private SqlSessionUtil(){};
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();
    static
    {
        try
        {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    public static SqlSession openSession()
    {
        SqlSession sqlSession = local.get();
        if (sqlSession == null)
        {
            sqlSession = sqlSessionFactory.openSession();
            local.set(sqlSession);
        }
        return sqlSession;
    }
    public static void close(SqlSession sqlSession)
    {
        if(sqlSession != null)
        {
            sqlSession.close();
            local.remove();
        }
    }
}
package com.powernode.mybatis.Test;

import com.powernode.mybatis.POJO.Car;
import com.powernode.mybatis.mappers.CarMapper;
import com.powernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

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

public class Test
{
    @org.junit.Test
    public void TestPojoSelect()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = mapper.selectById(5l);
        System.out.println(car);
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestSelectAll()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectAll();
        carList.forEach(car -> {
            System.out.println(car);
        });
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestBrand()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        //会报错,因为返回了多条记录了
        Car car = mapper.selectByBrand("比亚迪");
        System.out.println(car);
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestSelectByCarId()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByCarId(5L);
        carList.forEach(car -> {
            System.out.println(car);
        });
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestSelectByIdGetMap()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Map<String, Object> car = mapper.selectByIdGetMap(5l);
        System.out.println(car);
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestselectAllCar()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Map<String, Object>> maps = mapper.selectAllCar();
        maps.forEach(map ->{
            System.out.println(map);
        });
    }
}
package com.powernode.mybatis.Test;

import com.powernode.mybatis.POJO.Car;
import com.powernode.mybatis.mappers.CarMapper;
import com.powernode.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

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

public class Test
{
    @org.junit.Test
    public void TestPojoSelect()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Car car = mapper.selectById(5l);
        System.out.println(car);
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestSelectAll()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectAll();
        carList.forEach(car -> {
            System.out.println(car);
        });
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestBrand()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        //会报错,因为返回了多条记录了
        Car car = mapper.selectByBrand("比亚迪");
        System.out.println(car);
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestSelectByCarId()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByCarId(5L);
        carList.forEach(car -> {
            System.out.println(car);
        });
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestSelectByIdGetMap()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        Map<String, Object> car = mapper.selectByIdGetMap(5l);
        System.out.println(car);
        SqlSessionUtil.close(sqlSession);
    }
    @org.junit.Test
    public void TestselectAllCar()
    {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Map<String, Object>> maps = mapper.selectAllCar();
        maps.forEach(map ->{
            System.out.println(map);
        });
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值