引入依赖

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>2.0.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <version>8.0.13</version>
  10. </dependency>

配置数据源

  1. spring:
  2. datasource:
  3. url: jdbc:mysql://localhost:3306/study?useSSL=false&serverTimezone=GMT%2B8
  4. username: root
  5. password: root
  6. driver-class-name: com.mysql.cj.jdbc.Driver

创建Mapper

  1. @Mapper
  2. public interface TestMapper {
  3. /**
  4. * find Account by name
  5. * @param name user name
  6. * @return Account
  7. */
  8. @Select("SELECT name,money FROM test WHERE name=#{name}")
  9. Account findByName(@Param("name") String name);
  10. }

表结构

  1. +-------+------------+------+-----+---------+-------+
  2. | Field | Type | Null | Key | Default | Extra |
  3. +-------+------------+------+-----+---------+-------+
  4. | name | varchar(6) | YES | | NULL | |
  5. | money | int(11) | YES | | NULL | |
  6. +-------+------------+------+-----+---------+-------+

表数据

  1. +------+-------+
  2. | name | money |
  3. +------+-------+
  4. | A | 70 |
  5. | B | 200 |
  6. | C | 80 |
  7. +------+-------+

创建pojo

  1. @Data
  2. public class Account {
  3. private String name;
  4. private int money;
  5. }

测试

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class MybatisApplicationTests {
  4. @Autowired
  5. private TestMapper testMapper;
  6. @Test
  7. public void findTest() {
  8. String name = "B";
  9. Account account = testMapper.findByName(name);
  10. Assert.assertEquals(200, account.getMoney());
  11. }
  12. }

结果:通过