Mybatis 使用记录

发布时间:2023-12-18 01:14:00

Mybatis下载源码编译

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

  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.5.15-SNAPSHOT</version>

demo

参考 mybatis 源码分析 00:获取源码及 demo 准备
在这里插入图片描述

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

<?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="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>
    <!-- mapper 文件配置 -->
    <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-spring</artifactId>
  <version>3.0.3</version>
  <packaging>jar</packaging>

<mybatis.version>3.5.14</mybatis.version>
<spring.version>6.1.0</spring.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.boot</groupId>
  <artifactId>mybatis-spring-boot</artifactId>
  <version>3.0.3</version>
  <packaging>pom</packaging>
     <mybatis.version>3.5.14</mybatis.version>
    <mybatis-spring.version>3.0.3</mybatis-spring.version>
    <mybatis-freemarker.version>1.2.4</mybatis-freemarker.version>
    <mybatis-velocity.version>2.1.2</mybatis-velocity.version>
    <mybatis-thymeleaf.version>1.0.4</mybatis-thymeleaf.version>
    <spring-boot.version>3.2.0</spring-boot.version>

测试demo

添加 Mysql 依赖

在这里插入图片描述

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);
    }
}
文章来源:https://blog.csdn.net/qq_41146650/article/details/135002674
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。