lilele200706

 

SpringBoot之数据库连接

SpringBoot之数据库连接

1.整合JDBC

  1. 编写配置文件,数据库连接信息

  2. 测试连接信息

  • 自动注入DataSource

  • 获取数据库连接

  • SpringBoot中已经配置好了模板Bean:xxxxTemplate ,可以直接使用eg:jdbcTemplate,redisTemplate

  • 关闭连接

  1. 编写dao层

  • 自动注入JdbcTemplate

  • 使用JdbcTemplate增删改查

  • 返回数据

2.整合Druid数据源

只需要在配置文件数据源上添加type即可

spring:
datasource:
  username: root
  password: 123456
  url: jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
  driver-class-name: com.mysql.jdbc.Driver
  type: com.alibaba.druid.pool.DruidDataSource

   #SpringBoot默认是不配置这些属性值的,需要自己绑定
   #druid 数据源专有配置
  initialSize: 5
  minIdle: 5
  maxActive: 20
  maxWait: 60000
  timeBetweenEvictionRunsMillis: 60000
  minEvictable IdleTimeMillis: 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

Druid的强大之处

//Druid强大之处
@Configuration
public class DruidConfig {
   @Bean
   @ConfigurationProperties(prefix = "spring.datasource")
   public DataSource druidDataSource(){
       return new DruidDataSource();
  }
   //后台监控
   @Bean
   public ServletRegistrationBean statViewServlet(){
       ServletRegistrationBean<StatViewServlet> bean =
               new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
       //后台需要登录,设置账户密码
       HashMap<String,String> initParameters = new HashMap<>();
       initParameters.put("loginUsername","admin");//key是固定
       initParameters.put("loginPassword","123456");
       //允许谁可以访问
       initParameters.put("allow","");
       //initParameters.put("lele","192.168.112.112") 禁止谁访问
       //设置初始化参数
       bean.setInitParameters(initParameters);
       return bean;
  }
   @Bean
   public FilterRegistrationBean webStatFilter(){
       FilterRegistrationBean bean = new FilterRegistrationBean();
       bean.setFilter(new WebStatFilter());
       //可以过滤哪些请求
       HashMap<String,String> initParameters = new HashMap<>();
       //哪些可以不用过滤
       initParameters.put("exclusions","*.css,*.js,/druid/*");
       bean.setInitParameters(initParameters);
       return bean;
  }
}

3.整合Mybatis

  1. 建表,实体类

use school
create table user(
  id int(10) auto_increment,
  name varchar(20) not null default '匿名',
  password varchar(20) not null default '123456',
  primary key (id)
)ENGINE=InnoDB default charset =utf8

insert into user(name) values("张三"),("李四"),("王五"),("赵六"),("田七"),("吴九")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
   Integer id;
   String name;
   String password;
}
  1. 导入依赖mybatis-spring-boot-starter

 <dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>2.2.0</version>
</dependency>
  1. 配置文件application.yml

spring:
datasource:
  username: root
  password: 123456
  url: jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
  driver-class-name: com.mysql.cj.jdbc.Driver
  1. mybatis配置 写Mapper

@Mapper
@Repository
public interface UserMapper {
   List<User> queryAll();
}
  1. 写mapper.xml,在resources/mybatis/mapper目录下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
       "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="com.lele.mapper.UserMapper">
   <!--resultType: 返回类型,写别名,需要在配置文件配置别名 -->
   <select id="queryAll" resultType="User">
SELECT * FROM user
</select>
</mapper>

resultType: 返回类型,写别名,需要在配置文件配置别名application.yml

#整合mybatis
mybatis:
type-aliases-package: com.lele.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
  1. 业务层调用dao层

@RestController
public class UserController {
   @Autowired
   UserMapper userMapper;
    @RequestMapping("/list")
    public List<User> queryAll(){
       return userMapper.queryAll();
    }
}

 

posted on 2021-12-14 21:57  lilele200706  阅读(703)  评论(0)    收藏  举报

导航