Mybatis 使用记录

Mybatis 使用记录

  • Mybatis下载源码编译
    • demo
      • config.properties
      • mybatis-config.xml
      • UserMapper.xml
      • 测试代码
  • mybatis-spring 下载编译
    • demo
  • mybatis-spring-boot-starter
    • 测试demo
  • mybatis plus 编译

Mybatis下载源码编译

参考 mybatis 源码分析 00:获取源码及 demo 准备

  <groupId>org.mybatisgroupId>
  <artifactId>mybatisartifactId>
  <version>3.5.15-SNAPSHOTversion>

demo

参考 mybatis 源码分析 00:获取源码及 demo 准备
Mybatis 使用记录_第1张图片

config.properties

Cause: java.sql.SQLException: No suitable driver found for http://www.example.com (maven搭建mybatis出错)

driver=com.mysql.cj.jdbc.Driver
# 最好不要使用 url 字段
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username=root
password=root

mybatis-config.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties resource="study/config.properties">
    properties>
    <plugins>
        <plugin interceptor="study.SqlInterceptor">
        plugin>
    plugins>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC">
                <property name="..." value="..."/>
            transactionManager>
            
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="study/UserMapper.xml"/>
    mappers>
configuration>

UserMapper.xml

<?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="study.UserMapper">
    <select id="getUsers" resultType="study.User">
        select id, username from user
        <trim prefix="where" prefixOverrides="AND |OR">
            <if test="id != null">
                and id = #{id}
            </if>
        </trim>
        <if test="limit != null">
            limit #{limit}
        </if>
    </select>
    <cache/>
</mapper>

测试代码

将资源文件放到 resource 目录

@Intercepts({
    @Signature(type= Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class SqlInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement)args[0];
        BoundSql boundSql = ms.getBoundSql(args[1]);
        String sql = boundSql.getSql();
        System.out.println("执行的sql为:" + sql);
        return invocation.proceed();
    }
}

// 需要实现Serializable 接口,否则可能在使用二级缓存时报序列化异常
public class User implements Serializable {}


public interface UserMapper {
  List<User> getUsers(@Param("id") Long id, @Param("limit") Integer limit);
}

public static void main(String[] args) throws IOException {
    String resource = "study/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(inputStream);
    try (SqlSession sqlSession = factory.openSession()) {
      // 获取 mapper,进行查询操作
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      List<User> users = userMapper.getUsers(null, null);
      System.out.println(users);
    }
}

mybatis-spring 下载编译

下载 mybatis-spring 源码,比如3.0.3 版本,版本问题参考官网

  <artifactId>mybatis-springartifactId>
  <version>3.0.3version>
  <packaging>jarpackaging>

<mybatis.version>3.5.14mybatis.version>
<spring.version>6.1.0spring.version>

demo

就不需要准备 mybatis-config.xml 配置了, 如果编译报错,没有找到 ApplicationContext

@Configuration
@MapperScan("org.mybatis.demo.mapper")
public class Test {

  @Bean
  public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    // 设置数据源
    factoryBean.setDataSource(dataSource());
    // mapper.xml 文件路径
    Resource[] resources = new PathMatchingResourcePatternResolver()
      .getResources("classpath*:/mapper/**/*.xml");
    factoryBean.setMapperLocations(resources);
    return factoryBean.getObject();
  }

  @Bean
  public DataSource dataSource() throws Exception {
    Driver driver = new com.mysql.cj.jdbc.Driver();
    String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
    String username = "root";
    String password = "root";
    return new SimpleDriverDataSource(driver, url, username, password);
  }

  @Service
 static class UserService {
    @Autowired
    private UserMapper userMapper;
    public List<User> getUser(Long id, Integer limit) {
      return userMapper.getUsers(id, limit);
    }
 }


  public static void main(String[] args) {
    ApplicationContext application = new AnnotationConfigApplicationContext(Test.class);
    // 获取 userService 对象
    UserService userService = application.getBean(UserService.class);
    List<User> list = userService.getUser(null, 3);
    System.out.println(list);
  }
}

mybatis-spring-boot-starter

下载 spring-boot-starter

  <groupId>org.mybatis.spring.bootgroupId>
  <artifactId>mybatis-spring-bootartifactId>
  <version>3.0.3version>
  <packaging>pompackaging>
     <mybatis.version>3.5.14mybatis.version>
    <mybatis-spring.version>3.0.3mybatis-spring.version>
    <mybatis-freemarker.version>1.2.4mybatis-freemarker.version>
    <mybatis-velocity.version>2.1.2mybatis-velocity.version>
    <mybatis-thymeleaf.version>1.0.4mybatis-thymeleaf.version>
    <spring-boot.version>3.2.0spring-boot.version>

测试demo

添加 Mysql 依赖

Mybatis 使用记录_第2张图片

public interface UserMapper {
    @Select("select * from user")
    List<User> getUsers();
}

@SpringBootApplication
@MapperScan("demo.mapper")
public class ApplicationMain {

    @RestController
    static class TestController {
        @Autowired
        private UserMapper userMapper;

        @RequestMapping("/users")
        public String getUsers() {
            return userMapper.getUsers().toString();
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(ApplicationMain.class);
    }
}

mybatis plus 编译

修改编译版本 build.gradle

 configuration = [
        javaVersion = JavaVersion.VERSION_17
   ]

直接运行现有的测试类
Mybatis 使用记录_第3张图片

你可能感兴趣的:(Spring+spring,boot,mybatis)