springboot整合持久层JDBC mybaties 连接池
整合jdbc和事务
spring中的jdbc连接和事务是配置中的重要一环,在SpringBoot中该如何处理呢?
答案是不需要处理,我们只要找到SpringBoot提供的启动器即可:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
当然,不要忘了数据库驱动,SpringBoot并不知道我们用的什么数据库,这里我们选择MySQL:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
至于事务,SpringBoot中通过注解来控制。就是我们熟知的@Transactional
@Service public class UserService { @Autowired private UserMapper userMapper; public User queryById(Long id){ return this.userMapper.selectByPrimaryKey(id); } @Transactional public void deleteById(Long id){ this.userMapper.deleteByPrimaryKey(id); } }
5.3.整合连接池
其实,在刚才引入jdbc启动器的时候,SpringBoot已经自动帮我们引入了一个连接池:
HikariCP应该是目前速度最快的连接池了,我们看看它与c3p0的对比:
因此,我们只需要指定连接池参数即可:
# 连接四大参数 spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root # 可省略,SpringBoot自动推断 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.hikari.idle-timeout=60000 spring.datasource.hikari.maximum-pool-size=30 spring.datasource.hikari.minimum-idle=10
当然,如果你更喜欢Druid连接池,也可以使用Druid官方提供的启动器:
<!-- Druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency>
而连接信息的配置与上面是类似的,只不过在连接池特有属性上,方式略有不同:
#初始化连接数 spring.datasource.druid.initial-size=1 #最小空闲连接 spring.datasource.druid.min-idle=1 #最大活动连接 spring.datasource.druid.max-active=20 #获取连接时测试是否可用 spring.datasource.druid.test-on-borrow=true #监控页面启动 spring.datasource.druid.stat-view-servlet.allow=true
5.4.整合mybatis
5.4.1.mybatis
SpringBoot官方并没有提供Mybatis的启动器,不过Mybatis官网自己实现了:
<!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
配置,基本没有需要配置的:
# mybatis 别名扫描 mybatis.type-aliases-package=........ # mapper.xml文件位置,如果没有映射文件,请注释掉 mybatis.mapper-locations=classpath:mappers/*.xml
需要注意,这里没有配置mapper接口扫描包,因此我们需要给每一个Mapper接口添加@Mapper
注解,才能被识别。
@Mapper public interface UserMapper { }
5.4.2.通用mapper
通用Mapper的作者也为自己的插件编写了启动器,我们直接引入即可:
<!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency>
不需要做任何配置就可以使用了。
@Mapper public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User>{ }
5.5.启动测试
将controller进行简单改造:
@RestController public class HelloController { @Autowired private UserService userService; @GetMapping("/hello") public User hello() { User user = this.userService.queryById(8L); return user; } }