数据库连接池druid
- 添加依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- 在属性文件中配置
spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/tiger_springboot username: root password: root type: com.alibaba.druid.pool.DruidDataSource
- 实例化Druid对象
@Configuration public class DruidDBConfig { @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Bean public DataSource getDateSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); return druidDataSource; } }
- 打开监控中心
@Configuration public class DruidConfiguration { @Bean public ServletRegistrationBean druidRegist(){ ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(); servletRegistrationBean.setServlet(new StatViewServlet()); servletRegistrationBean.addUrlMappings("/druid/*"); servletRegistrationBean.addInitParameter("loginUsername","admin"); servletRegistrationBean.addInitParameter("loginPassword","admin"); return servletRegistrationBean; } @Bean public FilterRegistrationBean fiterRegist(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); filterRegistrationBean.addUrlPatterns("/*"); filterRegistrationBean.addInitParameter("exclusions",".js,*.git,*jpg,*.css,*.ico,/druid/*"); filterRegistrationBean.addInitParameter("profileEnable","true"); return filterRegistrationBean; } }
整合mybatis
- 添加依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
- 在属性文件中的添加配置
mybatis: mapper-locations: classpath:mapper/*.Mapper.xml
3创建一个实体类
@Data public class User { private int id; private String name; private int age; }
- 编写Dao
@Mapper public interface UserMapper { void save(User user); }
在resources/mapper中
<mapper namespace="com.cblue.demo05.mapper.UserMapper"> <insert id="save" parameterType="com.cblue.demo05.entity.User"> insert into user(name,age) values(#{name},#{age}); </insert> </mapper>
测试
@Test public void testAdd(){ User user = new User(); user.setName("aaa"); user.setAge(20); userMapper.save(user); }