SpringBoot-整合Mybatis(十六)
1.注解版Mybatis
在上一次的博客中我们介绍到我们配置好了数据源,接下来我们整合Mybatis
首先导入maven依赖
<!--spring--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
然后编写实体类
public class User { private int id; private String name; private String pwd; public User() { } public User(int id, String name, String pwd) { this.id = id; this.name = name; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
编写Mybatis的映射文件mapper
@Mapper public interface UserMapper { @Select("select *from user") List<User> selectUser(); @Delete("delete from user where id=#{id}") int deleteUser(int id); }
我们需要在类上加上注解 @mapper 告诉Springboot这是一个mybatis的映射文件。
接下来编写controller
@RestController public class UserController { @Autowired UserMapper userMapper; @GetMapping("/user") public String getUser(){ List<User> users = userMapper.selectUser(); for (User user : users) { System.out.println(user); } return "OK"; } @GetMapping("/del") public int deleteUser(){ int i = userMapper.deleteUser(4); return i; } }
测试运行。OK
如果我们不在mapper映射文件上加上注解,则我们需要在启动类上加上扫描包的注解
使用MapperScan批量扫描所有的Mapper接口; @MapperScan(value = "org.west.demo.mapper") @SpringBootApplication public class SpringBoot06DataMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot06DataMybatisApplication.class, args); } }
自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;
@org.springframework.context.annotation.Configuration public class MyBatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer(){ @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }
2.配置版mybatis
当然了配置版的mybatis就没有这么少的代码可以实现,相对好理解一点。和我们之前操作mybatis基本一样,只不过需要注意的一点就是在springBoot的配置文件中引入mybatis的配置文件。
mybatis: config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置 mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置
更多使用参照
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/