关于spring-boot结合mybatis相关问题

1.新建spring-boot工程

2.加入相应jar包引用


org.springframework.boot
spring-boot-starter-jdbc


org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.1



mysql
mysql-connector-java
runtime

3.配置数据源

spring.datasource.url=jdbc:mysql://*.*.*.*:3306/cloud?useUnicode=true&characterEncoding=UTF-8&useSSL=true
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

4.在application.properties或bootstrap.properties中加入mybatis配置

mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mappers/*.xml

5.在resource目录下新建mybatis-config.xml


"http://mybatis.org/dtd/mybatis-3-config.dtd">


6.在resource目录下新建mappers文件夹,并新建文件test-sqlMap.xml


"http://mybatis.org/dtd/mybatis-3-mapper.dtd">




7.在spring-boot启动文件上加入@MapperScan("com.cloud.mapper")将所有的mapper接口加入mybatis

@EnableEurekaClient
@MapperScan("com.cloud.mapper")
@SpringBootApplication
public class ServiceCommonApplication {

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

8.新建接口TestMapper

public interface TestMapper  {

public TestVO queryUser(Map paramMap);

}

9.新建VO类

public class TestVO {

private Integer id;

private String name;

private String mail;

private String address;
}

10.测试类

@Autowired
private TestMapper testMapper;
@GetMapping("testSql")
public String findUser(String name){
Map paramMap = new HashMap<>();
paramMap.put("name",name);
TestVO user = testMapper.queryUser(paramMap);
if (user == null) return "-9999";
return JSON.toJSONString(user);
}

总结:采用以上方式基本可以将spring-boot与mybatis结合起来。回头再看一下test-sqlMap.xml配置文件。发现比较麻烦,首先每一个mapper配置文件中只能有一个namespace,这意味着,每一个mapper配置文件中只能存放一个与VO对象相匹配的CRUD相关操作。这与JPA操作时,每一个 Repository接口都与Entity实体相对应类似,基本都用于采用单表操作。对于多表操作缺乏灵活性。

你可能感兴趣的:(关于spring-boot结合mybatis相关问题)