springboot整合mybatis编写自定义的转换器(boolean到tinyint)

写一个typeHandle(具体JDBC和JAVA映射查看表)

mybatis官网

package com.gyg.converter;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BooleanAndIntConverter extends BaseTypeHandler<Boolean> {
    //从java到数据库

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
        if (parameter) {
            ps.setInt(i, 1);
        } else {
            ps.setInt(i, 0);
        }
    }

    //从DB->Java代码
    @Override
    public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int man = rs.getInt(columnName);
        return man == 1 ? true : false;
    }

    @Override
    public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int man = rs.getInt(columnIndex);
        return man == 1 ? true : false;
    }

    //通过存储过程取数据
    @Override
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int man = cs.getInt(columnIndex);
        return man == 1 ? true : false;
    }
}

配置yml文件

这里 mapper-locations 配置时加classpath更好,因为是具体到某个xml文件,所以采用,包名的那种形式不好
且java和resource编译之后都会放在classes中,classpath指代的路径之一就是这个classpanth。

提一嘴。编译的时候不会编译java里面的非java文件(例如mapper.xml),所以需要在pom文件配置如文章末尾

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/gyg_school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource

mybatis:
  type-aliases-package: com.gyg.entity
  mapper-locations: classpath:/com/gyg/mapper/xml/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-handlers-package: com.gyg.config.mybatis

logging:
  level:
    com.gyg: info

文件路径

这里采用的是,mapper和xml同意目录的情况,即使目录不同,也没关系,配置 mapper-locations即可
文件路径

mapper的xml文件编写

提一嘴,这里的id要对应mapper接口的抽象方法。
插入需要在sql语句中生命转换器,查询需要在resultMap里面转换

<?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.gyg.mapper.GradesMapper">
    <insert id="insertOne" parameterType="grades">
        INSERT INTO grades(uid, tid, lid,  score, pass)
        VALUES (#{uid}, #{tid}, #{lid}, #{score}, #{pass,typeHandler=com.gyg.config.mybatis.BooleanToTinyintTypeHandle})
    </insert>

    <insert id="insertOne2" parameterType="grade">
        INSERT INTO grades(uid, tid, lid, score, pass)
        VALUES (#{uid}, #{tid}, #{lid}, #{score}, #{pass})
    </insert>
    <select id="selectOne" parameterType="int" resultMap="map">
        select *
        from grades
        where id=#{id}
    </select>

    <resultMap id="map" type="grades">
        <id column="id" property="id"/>
        <result property="pass" column="pass" jdbcType="TINYINT" javaType="boolean" typeHandler="com.gyg.config.mybatis.BooleanToTinyintTypeHandle"/>
    </resultMap>
</mapper>

@mapper和@Properties的区别

@Mapper是mybatis的注解,@properties是spring的注解,随便写哪一个都会在spring中生成bean。因为都是基于cglib
动态代理,需要在Application启动入口配置mapperScan

@Repository
//@Mapper
public interface GradesMapper {
    /**
     * XXX
     * @author gyg
     * @param grades
     * @return
     **/
    void insertOne(Grades grades);
    void insertOne2(Grade grade);
    Grades selectOne(Integer id);
}

启动类配置MapperScan

@SpringBootApplication
@MapperScan("com.gyg.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

测试

@SpringBootTest
@RunWith(SpringRunner.class)
public class GradesServiceImplTest {
    @Autowired
    GradesService gradesService;

    @Test
    public void insertOne(){
        Grades grades = new Grades();
        grades.setLid(1);
        grades.setTid(1);
        grades.setUid(3);
        grades.setScore(58.5);
        grades.setPass(true);
        try {
            gradesService.insertOne(grades);
        }catch (Exception ignored){};
        System.out.println("插入完成!");
    }

    @Test
    public void insertOne2(){
        Grade grades = new Grade();
        grades.setLid(1);
        grades.setTid(1);
        grades.setUid(2);
        grades.setScore(98.1);
        grades.setPass(1);
        try {
            gradesService.insertOne2(grades);
            System.out.println("插入完成!");
        }catch (Exception ignored){};
    }

    @Test
    public void selectOne(){
        Grades grades = gradesService.selectOne(1);
        if (grades!=null) {
            System.out.println(grades.toString());
        }
    }
}

7. 源码和pom

pom

<?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>org.example</groupId>
    <artifactId>school</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>

        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>

            </resource>
        </resources>
    </build>

</project>

github地址
转换器demo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis中,如果要使用自定义的SQL语句,可以按照以下步骤进行操作: 1. 在Spring Boot的启动类上使用@MapperScan注解,并指定要扫描的mapper接口的包路径。例如,使用@MapperScan("com.springmybatis.mapper")注解来扫描com.springmybatis.mapper包下的mapper接口。 2. 创建一个Controller类,使用@RestController注解来标识这是一个Restful接口的控制器类。 3. 在Controller类中,使用@Autowired注解自动注入对应的Service实例。例如,使用@Autowired UserServiceImpl userService来注入UserServiceImpl实例。 4. 在Controller类中定义自定义的SQL查询方法,并使用@GetMapping注解来标识这是一个GET请求的处理方法。例如,使用@GetMapping("/seAll")注解来处理/seAll的GET请求。 5. 在自定义的SQL查询方法中,调用相应的Service方法执行自定义的SQL查询。例如,使用userService.seAll()来执行自定义的SQL查询,并返回查询结果。 通过以上步骤,你可以在Spring Boot整合MyBatis中使用自定义的SQL查询语句。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [springboot整合Mybatis-plus 且用xml自定义sql](https://blog.csdn.net/qq_47848696/article/details/117930682)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [springboot 整合 mybatis 注解 sql 语句](https://blog.csdn.net/wsjzzcbq/article/details/91492700)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值