application.yml配置
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mydb1?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
默认数据源是:Hikari 天然集成日志监控
JDBC
SpringBoot整合了jdbc的crud方法 我们可以直接导入jdbcTemplate对象 并自动装配就可以使用
@Autowired
JdbcTemplate jdbcTemplate;
jdbc增删改查回顾
@GetMapping("/all")
public List<Map<String, Object>> all() {
String sql="select * from user";
List<Map<String, Object>> Map = jdbcTemplate.queryForList(sql);
return Map;
}
@GetMapping("/add")
public String add(){
String sql="insert into user (id,name,password) values (9,'猪八戒','123456')";
jdbcTemplate.execute(sql);
return "add--ok";
}
@GetMapping("/delete/{id}")
public String delete(@PathVariable("id") int id){
String sql="delete from user where id="+id;
jdbcTemplate.execute(sql);
return "detele-ok";
}
@GetMapping("/update/{id}/{password}")
public String update(@PathVariable("id") int id, @PathVariable("password") String password){
String sql="update user set password="+password+" where id="+id;
jdbcTemplate.execute(sql);
return "update--ok";
}
后面使用restful风格 进行传参 避免程序写死
Druid数据源配置
- 依赖导入
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
- 在配置中修改数据源的类型为druid
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mydb1?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
主要是下面的
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
-
在资源文件下添加log4j的配置
log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
-
在配置类中将bean与yaml配置结合
@Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } }
这样子 druid就替换了springboot默认的数据源hikari
但是 druid的强大之处是它可以配置一个后台的监听,来监听我们的程序运行 我们只需要配置一下 即可
//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
//后台监控
//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
// 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
initParams.put("loginPassword", "admin"); //后台管理界面的登录密码
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow", "");
//deny:Druid 后台拒绝谁访问
//initParams.put("hh", "192.168.1.20");表示禁止此ip访问
//设置初始化参数
bean.setInitParameters(initParams);
return bean;
}
然后启动网页 访问 http://localhost:8080/druid/sql.html
这样子 一个druid数据源就配置完成了
我们还可以通过druid来配置过滤器
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParams);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
整合Mybatis
- 导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
-
编写实体类
-
编写Mapper接口
-
注册Mapper
在接口类上添加@Repository注解 表明这个接口被Spring接管
@Mapper @Repository public interface UserMapper { ArrayList<User> getall(); }
可以在Mapper接口的上面添加@Mapper注解来注册mapper
也可以在启动类上面添加@MapperScan()注解 括号里填mapper的路径 com.llf.Mapper
@SpringBootApplication @MapperScan("com.llf.Mapper") public class SpringbootDataApplication { public static void main(String[] args) { SpringApplication.run(SpringbootDataApplication.class, args); } }
-
编写Mapper.xml
与以前不同,Mapper.xml要放在resource目录下 为了区分 在resource目录下创建 mybatis/Mapper/**.xml
-
配置xml文件 在yaml配置文件中
#注册xml文件 起别名 mybatis: mapper-locations: classpath:mybatis/Mapper/*.xml type-aliases-package: com.llf.pojo
-
编写service接口
-
编写Service实现类
@Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; @Override public ArrayList<User> getall() { return userMapper.getall(); } }
-
测试
@Autowired private UserServiceImpl userService; @Test public void all(){ ArrayList<User> getall = userService.getall(); for (User user : getall) { System.out.println(user); } }
说明mybatis整合完成