mybatis小技巧
#{}和${}的区别
${}的效果
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: Unknown column '新能源' in 'where clause'
### The error may exist in CarMapper.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: 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             car_type = 新能源
### Cause: java.sql.SQLSyntaxErrorException: Unknown column '新能源' in 'where clause'
因为${}不会生成?然后直接以字段的形式填入了Sql语句
区别:
#{}底层使用prepareStatement,先进行编译,然后用?传值
${}底层使用statement,先进行拼接语句,再对语句进行编译(存在SQL注入风险)
可以扭曲原SQL语句的含义
如果向SQL中拼接表名,就需要使用${}
现实业务中,可能存在分表储存的情况,因为一张表存的话,数据量过大,查询效率比较低
可以将这些数据有规律的分表储存,这样在查询的时候效率比较高,因为扫描的数据量变少了
日志表,专门存储日志信息的,如果t_log,这个表中每天都会产生很多log,慢慢这个表内容会爆炸
可以每天生成一张表,每张表以当天日期作为名称
如果我们需要知道某天的日志信息怎么办
假设今天20230901,那么直接查询t_log_20230901即可
批量删除的写法,如何一次删除多条记录
第一种,delete from xxx where id = ? or id = ? or id = ?
第二种,delete from t_car where id in(1,2,3);
//因为我们是通过拼接SQL的方式实现的,所以占位符会导致留下单引号
所以我们需要使用${}这个底层调用statement的方法的,因为它是先拼接后编译
#{}这个底层是preparedStatement,会先编译后拼接SQL语句
模糊查询like做法:需求根据汽车品牌进行查询
select * from t_car where brand like '%奔驰%';
select * from t_car where brand like '%比亚迪%';
这个位置也不能用底层preparedStatement的#{}因为,会添加上''导致无法实现语义
第一种方案${}
第二种方案:使用concat函数,这个是mysql数据库专门用于字符串拼接的一个函数
concat('%',#{brand},'%')
第三种方案:concat('%','${brand}','%')
第四种方案:concat("%"#{brand}"%")
nameSpace不能起别名,必须是全限定类名,带有包名在内的
<typeAliases>
<!--        Type属性是指定哪个属性起别名,alias是指定别名-->
        <typeAlias type="com.powernode.mybatis.POJO.Car" alias="Car"></typeAlias>
        <typeAlias type="com.powernode.mybatis.POJO.Log" alias="Log"></typeAlias>
    </typeAliases>
    TypeAliases这个属性可以给我们的类起别名,起到简化的效果,必须在settings标签后配置
<TypeAliases>如果我们不指定别名,就自动以类名作为别名,在namespace下使用的时候,不区分大小写
Mapper标签可以用三个配置文件,resource和url和class,要求类的根路径必须有这个文件
resource是从根路径加载资源文件,url通过绝对路径找文件,这种方式移植性太差
class写的是全限定接口名,带有包名的,这个位置提供的是Mapper接口的全限定类名带包名的
如果写的是class,mybatis会自动去com.powernode.mybatis.Mapper下找这个XML文件
也就是说,这个Mapper接口必须是和xml在同一个文件夹下
建包只能在java包下实现,我们在Resource下只能建Directory而且他需要用/做层级切割





mybatis小技巧
#{}和${}的区别
${}的效果
org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.sql.SQLSyntaxErrorException: Unknown column '新能源' in 'where clause'
### The error may exist in CarMapper.xml
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: 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             car_type = 新能源
### Cause: java.sql.SQLSyntaxErrorException: Unknown column '新能源' in 'where clause'
因为${}不会生成?然后直接以字段的形式填入了Sql语句
区别:
#{}底层使用prepareStatement,先进行编译,然后用?传值
${}底层使用statement,先进行拼接语句,再对语句进行编译(存在SQL注入风险)
可以扭曲原SQL语句的含义
如果向SQL中拼接表名,就需要使用${}
现实业务中,可能存在分表储存的情况,因为一张表存的话,数据量过大,查询效率比较低
可以将这些数据有规律的分表储存,这样在查询的时候效率比较高,因为扫描的数据量变少了
日志表,专门存储日志信息的,如果t_log,这个表中每天都会产生很多log,慢慢这个表内容会爆炸
可以每天生成一张表,每张表以当天日期作为名称
如果我们需要知道某天的日志信息怎么办
假设今天20230901,那么直接查询t_log_20230901即可
批量删除的写法,如何一次删除多条记录
第一种,delete from xxx where id = ? or id = ? or id = ?
第二种,delete from t_car where id in(1,2,3);
//因为我们是通过拼接SQL的方式实现的,所以占位符会导致留下单引号
所以我们需要使用${}这个底层调用statement的方法的,因为它是先拼接后编译
#{}这个底层是preparedStatement,会先编译后拼接SQL语句
模糊查询like做法:需求根据汽车品牌进行查询
select * from t_car where brand like '%奔驰%';
select * from t_car where brand like '%比亚迪%';
这个位置也不能用底层preparedStatement的#{}因为,会添加上''导致无法实现语义
第一种方案${}
第二种方案:使用concat函数,这个是mysql数据库专门用于字符串拼接的一个函数
concat('%',#{brand},'%')
第三种方案:concat('%','${brand}','%')
第四种方案:concat("%"#{brand}"%")
nameSpace不能起别名,必须是全限定类名,带有包名在内的
<typeAliases>
<!--        Type属性是指定哪个属性起别名,alias是指定别名-->
        <typeAlias type="com.powernode.mybatis.POJO.Car" alias="Car"></typeAlias>
        <typeAlias type="com.powernode.mybatis.POJO.Log" alias="Log"></typeAlias>
    </typeAliases>
    TypeAliases这个属性可以给我们的类起别名,起到简化的效果,必须在settings标签后配置
<TypeAliases>如果我们不指定别名,就自动以类名作为别名,在namespace下使用的时候,不区分大小写
Mapper标签可以用三个配置文件,resource和url和class,要求类的根路径必须有这个文件
resource是从根路径加载资源文件,url通过绝对路径找文件,这种方式移植性太差
class写的是全限定接口名,带有包名的,这个位置提供的是Mapper接口的全限定类名带包名的
如果写的是class,mybatis会自动去com.powernode.mybatis.Mapper下找这个XML文件
也就是说,这个Mapper接口必须是和xml在同一个文件夹下
建包只能在java包下实现,我们在Resource下只能建Directory而且他需要用/做层级切割
<?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>
<!--        Type属性是指定哪个属性起别名,alias是指定别名-->
<!--        <typeAlias type="com.powernode.mybatis.POJO.Car" alias="Car"></typeAlias>-->
<!--        <typeAlias type="com.powernode.mybatis.POJO.Log" alias="Log"></typeAlias>-->
<!--        写一个包名,将这些类自动指定别名,别名默认为类的名字-->
        <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>
        <!--        指定xml文件的路径,自动从根路径下找资源-->
<!--        <mapper class="com.powernode.mybatis.Mapper.CarMapper"></mapper>-->
<!--        <mapper class="com.powernode.mybatis.Mapper.LogMapper"></mapper>-->
<!--                url属性,是从绝对路径下加载资源的,语法格式是file:///加绝对路径-->
        <!--        <mapper resource="CarMapper.xml" url="file:///d:/CarMapper.xml"></mapper>-->
        <package name="com.powernode.mybatis.Mapper"/>
    </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>
<!--        Type属性是指定哪个属性起别名,alias是指定别名-->
<!--        <typeAlias type="com.powernode.mybatis.POJO.Car" alias="Car"></typeAlias>-->
<!--        <typeAlias type="com.powernode.mybatis.POJO.Log" alias="Log"></typeAlias>-->
<!--        写一个包名,将这些类自动指定别名,别名默认为类的名字-->
        <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>
        <!--        指定xml文件的路径,自动从根路径下找资源-->
<!--        <mapper class="com.powernode.mybatis.Mapper.CarMapper"></mapper>-->
<!--        <mapper class="com.powernode.mybatis.Mapper.LogMapper"></mapper>-->
<!--                url属性,是从绝对路径下加载资源的,语法格式是file:///加绝对路径-->
        <!--        <mapper resource="CarMapper.xml" url="file:///d:/CarMapper.xml"></mapper>-->
        <package name="com.powernode.mybatis.Mapper"/>
    </mappers>
</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" ?>

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

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.powernode.mybatis.Mapper.CarMapper">
    <delete id="deleteBatch">
        delete from
            t_car
        where
            car_num
        in
            (${carNums});
    </delete>
    <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}%'
--             brand like concat('%',#{brand},'%')
            brand like concat('%','${brand}','%')
            brand like concat("%"#{brand}"%")
    </select>
    <select id="selectByCarType" 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
            car_type = #{carType}
    </select>
    <select id="selectAllByAscOrDesc" 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
        order by
            guide_price ${DescOrAsc};
    </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.Mapper.CarMapper">
    <delete id="deleteBatch">
        delete from
            t_car
        where
            car_num
        in
            (${carNums});
    </delete>
    <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}%'
--             brand like concat('%',#{brand},'%')
            brand like concat('%','${brand}','%')
            brand like concat("%"#{brand}"%")
    </select>
    <select id="selectByCarType" 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
            car_type = #{carType}
    </select>
    <select id="selectAllByAscOrDesc" 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
        order by
            guide_price ${DescOrAsc};
    </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.Mapper.LogMapper">
    <select id="selectAllByTable" resultType="Log">
        select
            *
        from
            t_log_${date};
    </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.Mapper.LogMapper">
    <select id="selectAllByTable" resultType="Log">
        select
            *
        from
            t_log_${date};
    </select>
</mapper>
package com.powernode.mybatis.Mapper;

import com.powernode.mybatis.POJO.Car;

import java.util.List;

public interface CarMapper
{
    //根据汽车类型,获取汽车信息
    List<Car> selectByCarType(String carType);
    //查询所有的汽车信息,通过DESC或者ASC升降序
    List<Car> selectAllByAscOrDesc(String AscOrDesc);
    //根据ID进行批量删除
    int deleteBatch(String carNums);
    List<Car> selectByBrand(String brand);
}
package com.powernode.mybatis.Mapper;

import com.powernode.mybatis.POJO.Car;

import java.util.List;

public interface CarMapper
{
    //根据汽车类型,获取汽车信息
    List<Car> selectByCarType(String carType);
    //查询所有的汽车信息,通过DESC或者ASC升降序
    List<Car> selectAllByAscOrDesc(String AscOrDesc);
    //根据ID进行批量删除
    int deleteBatch(String carNums);
    List<Car> selectByBrand(String brand);
}
package com.powernode.mybatis.Mapper;

import com.powernode.mybatis.POJO.Log;

import java.util.List;

public interface LogMapper
{
    //根据日期查询不同的表,获取表中所有的日志
    List<Log> selectAllByTable(String time);
}
package com.powernode.mybatis.Mapper;

import com.powernode.mybatis.POJO.Log;

import java.util.List;

public interface LogMapper
{
    //根据日期查询不同的表,获取表中所有的日志
    List<Log> selectAllByTable(String time);
}
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.POJO;

public class Log
{
    private Long id;
    private String log;
    private String time;

    @Override
    public String toString() {
        return "Log{" +
                "id=" + id +
                ", log='" + log + '\'' +
                ", time='" + time + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

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

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public Log(Long id, String log, String time) {
        this.id = id;
        this.log = log;
        this.time = time;
    }

    public Log() {
    }
}
package com.powernode.mybatis.POJO;

public class Log
{
    private Long id;
    private String log;
    private String time;

    @Override
    public String toString() {
        return "Log{" +
                "id=" + id +
                ", log='" + log + '\'' +
                ", time='" + time + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

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

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public Log(Long id, String log, String time) {
        this.id = id;
        this.log = log;
        this.time = time;
    }

    public Log() {
    }
}
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 SqlSessionUtils
{
    private SqlSessionUtils(){}
    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 SqlSessionUtils
{
    private SqlSessionUtils(){}
    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.Mapper.CarMapper;
import com.powernode.mybatis.Mapper.LogMapper;
import com.powernode.mybatis.POJO.Car;
import com.powernode.mybatis.POJO.Log;
import com.powernode.mybatis.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.Iterator;
import java.util.List;

public class CarMapperTest
{
    @Test
    public void TestMapper()
    {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByCarType("新能源");
        carList.forEach(car ->
        {
            System.out.println(car);
        });
        SqlSessionUtils.close(sqlSession);
    }
    @Test
    public void TestDescOrAsc()
    {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectAllByAscOrDesc("DESC");
        carList.forEach(car -> {
            System.out.println(car);
        });
        SqlSessionUtils.close(sqlSession);
    }
    @Test
    public void TestLog()
    {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        LogMapper mapper = sqlSession.getMapper(LogMapper.class);
        List<Log> logs = mapper.selectAllByTable("20230902");
        Iterator<Log> iterator = logs.iterator();
        while(iterator.hasNext())
        {
            System.out.println((Log)iterator.next());
        }
    }
    @Test
    public void TestDelete()
    {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int count = mapper.deleteBatch("1003,1111");
        System.out.println(count);
        sqlSession.commit();
        SqlSessionUtils.close(sqlSession);
    }
    @Test
    public void SelectByBrandLike()
    {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> carList = mapper.selectByBrand("比亚迪");
        carList.forEach(car -> {
            System.out.println(car);
        });
    }
}
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐