SpringBoot —— 6、数据访问

目录

1、SQL

1.1、数据源的自动配置-HikariDataSource

1.1.1、导入依赖

1.1.2、自动配置的类

1.1.3、修改配置项

1.1.4、测试

2、使用 Druid 数据源

2.1、自定义方式

2.1.1、创建数据源

2.2、监控页功能 

2.2.1、StatViewServlet 开启监控页功能 及 防火墙

2.2.2、配置WebStatFilter

2.3、使用官方 starter 方式

2.3.1、引入 starter 依赖

2.3.2、在 application.yaml 中进行配置

3、整合 MyBatis 操作

3.1、引入 starter

3.2、配置模式

3.3、注解模式

3.4、混合模式


1、SQL

1.1、数据源的自动配置-HikariDataSource

1.1.1、导入依赖

mysql 版本 SpringBoot 已设置

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

若想要修改驱动的版本,可以在下面直接设置版本(maven的就近依赖原则)

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

或者在 pom.xml 的 properties 中设置版本

    <properties>
        <mysql.version>5.1.38</mysql.version>
    </properties>

1.1.2、自动配置的类

  • DataSourceAutoConfiguration : 数据源的自动配置

    • 修改数据源相关的配置:spring.datasource

    • 数据库连接池的配置,是自己容器中没有DataSource才自动配置的

    • 底层配置好的连接池是:HikariDataSource

  • DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置

  • JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud

    • 可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc"**) 来修改JdbcTemplate

    • @Bean@Primary JdbcTemplate;容器中有这个组件
  • JndiDataSourceAutoConfiguration: jndi的自动配置

  • XADataSourceAutoConfiguration: 分布式事务相关的

1.1.3、修改配置项

在 application.yaml 中修改配置项

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&useSSL=false
    username: root
    password: zyj123
    driver-class-name: com.mysql.jdbc.Driver

1.1.4、测试

@SpringBootTest
class Boot05WebAdminApplicationTests {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    void contextLoads() {
        Long aLong = jdbcTemplate.queryForObject("select count(*) from stu", Long.class);
        System.out.println(aLong);
    }

}

2、使用 Druid 数据源

druid官方github地址:druid

整合第三方技术的两种方式

  • 自定义
  • 找starter

2.1、自定义方式

2.1.1、创建数据源

① 引入依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>

② 设置数据源的相关属性

@Configuration
public class MyDataSourceConfig {

    // 默认的自动配置是判断容器中没有才会自动配置 @ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
    @Bean
    @ConfigurationProperties("spring.datasource") //设置与application.yaml中的属性进行绑定
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();


        return druidDataSource;
    }

}

application.yaml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&useSSL=false
    username: root
    password: zyj123
    driver-class-name: com.mysql.jdbc.Driver
  jdbc:
    template:
      query-timeout: 3 #设置查询超时的实践(单位:秒)

2.2、监控页功能 

监控页首页:http://localhost:8080/druid/index.html 

2.2.1、StatViewServlet 开启监控页功能 及 防火墙

官方文档(开启监控页功能):配置_StatViewServlet配置 · alibaba/druid Wiki · GitHub 

官方文档(防火墙):配置 wallfilter · alibaba/druid Wiki · GitHub

StatViewServlet的用途包括:

  • 提供监控信息展示的html页面
  • 提供监控信息的JSON API

设置 StatViewServlet

@Configuration
public class MyDataSourceConfig {

    // 默认的自动配置是判断容器中没有才会自动配置 @ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
    @Bean
    @ConfigurationProperties("spring.datasource") //设置与application.yaml中的属性进行绑定
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        // stat:加入监控功能
        // wall:防火墙
        druidDataSource.setFilters("stat,wall");
        return druidDataSource;
    }

    // 配置Druid的监控页功能
    @Bean
    public ServletRegistrationBean StatViewServlet(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> statViewServletServletRegistrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        return statViewServletServletRegistrationBean;
    }

}

2.2.2、配置WebStatFilter

官方文档:https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_%E9%85%8D%E7%BD%AEWebStatFilter

@Configuration
public class MyDataSourceConfig {

    // 默认的自动配置是判断容器中没有才会自动配置 @ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
    @Bean
    @ConfigurationProperties("spring.datasource") //设置与application.yaml中的属性进行绑定
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        // 加入监控功能
        druidDataSource.setFilters("stat");
        return druidDataSource;
    }

    // 配置Druid的监控页功能
    @Bean
    public ServletRegistrationBean StatViewServlet(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> statViewServletServletRegistrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        return statViewServletServletRegistrationBean;
    }

    // WebStatFilter 用于采集web-jdbc关联监控的数据。
    @Bean
    public FilterRegistrationBean WebStatFilter(){
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); //不拦截的路径
        return filterRegistrationBean;
    }

}

2.3、使用官方 starter 方式

官方文档:https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

2.3.1、引入 starter 依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>

2.3.2、在 application.yaml 中进行配置

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&useSSL=false
    username: root
    password: zyj123
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      aop-patterns: com.zyj.boot05webadmin.*  #设置spring监控的包

      filters: stat,wall  #底层开启功能,stat(sql监控),wall(防火墙)

      stat-view-servlet:  #配置监控页功能
        enabled: true  #开启监控页功能
        login-username: admin  #设置监控页的登录名
        login-password: 123456   #设置监控页的密码
        reset-enable: false  #是否有重置按钮

      web-stat-filter:  #监控web
        enabled: true  #开启监控
        url-pattern: /*  #监控的请求
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'  #排除的请求

      filter:
        stat:     #对上面filters里面的stat的详细配置
          enabled: true
          log-slow-sql: true
        wall:
          enabled: true  #开启防火墙

3、整合 MyBatis 操作

官方文档:https://github.com/mybatis

3.1、引入 starter

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

3.2、配置模式

  • 全局配置文件

  • SqlSessionFactory: 自动配置好了

  • SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession

  • @Import(AutoConfiguredMapperScannerRegistrar.class);

  • Mapper: 只要我们写的操作MyBatis的接口标准了 @Mapper 就会被自动扫描进

① 导入mybatis官方starter

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

② 编写mapper接口。使用@Mapper注解

@Mapper
public interface PersonMapper {

    public Person getPersonById(Long id);

}

③ 编写sql映射文件并绑定mapper接口。PersonMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zyj.boot05webadmin.mapper.PersonMapper">
    <!-- public Person getPersonById(Long id); -->
    <select id="getPersonById" resultType="com.zyj.boot05webadmin.bean.Person">
        select * from user where id = #{id}
    </select>
</mapper>

④ 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
    username: root
    password: zyj123
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      aop-patterns: com.zyj.boot05webadmin.*  #设置spring监控的包

      filters: stat,wall,slf4j  #底层开启功能,stat(sql监控),wall(防火墙)

      stat-view-servlet:  #配置监控页功能
        enabled: true  #开启监控页功能
        login-username: admin  #设置监控页的登录名
        login-password: 123456   #设置监控页的密码
        reset-enable: false  #是否有重置按钮

      web-stat-filter:  #监控web
        enabled: true  #开启监控
        url-pattern: /*  #监控的请求
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'  #排除的请求

      filter:
        stat:     #对上面filters里面的stat的详细配置
          enabled: true
          log-slow-sql: true
        wall:
          enabled: true  #开启防火墙

#配置mybatis
mybatis:
  #config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:   #设置了configuration后就不能写上面的config-location,否则会引起冲突
    #可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
    map-underscore-to-camel-case: true  #设置根据驼峰命名自动装配

3.3、注解模式

在 mapper 使用注解 

注:在主程序类使用@MapperScan("com.zyj.admin.mapper") 简化,其他的接口就可以不用标注@Mapper注解 

@Mapper
public interface CityMapper {

    @Select("select * from city where id = #{id}")
    public City getById(Long id);

    @Insert("insert into city(`name`, `state`, `country`) values(#{name}, #{state}, #{country})")
    @Options(useGeneratedKeys = true, keyProperty = "id")  //设置id为自增主键
    public void insert(City city);

}

3.4、混合模式

mapper 使用 注解 和 xml同时配置 

@Mapper
public interface CityMapper {

    @Select("select * from city where id = #{id}")
    public City getById(Long id);

    public void insert(City city);

}

4、整合 MyBatis-Plus 完成CRUD

官网:MyBatis-Plus

建议安装 MybatisX 插件

4.0、准备工作

CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")  // 设置该实体类对应的表名
public class Users {

    private Long id;
    private String name;
    private Integer age;
    private String email;

}

4.1、整合MyBatis-Plus

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

自动配置:

  • MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对mybatis-plus的定制
  • SqlSessionFactory 自动配置好。底层是容器中默认的数据源
  • mapperLocations 自动配置好的。有默认值。classpath*:/mapper/**/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
  • 容器中也自动配置好了 SqlSessionTemplate
  • @Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan("com.atguigu.admin.mapper") 批量扫描就行

优点:

  • 只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力

4.2、CURD 功能

4.2.1、添加 mapper、service 及其实现类 

UsersMapper

@Mapper
public interface UsersMapper extends BaseMapper<Users> {
}

UsersService

public interface UsersService extends IService<Users> {
}

UsersServiceImpl 

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
}

4.2.2、添加开启分页插件的配置类

@Configuration
public class MyBatisConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 创建分页拦截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 设置请求的页面大于最大页后操作,true调回首页,false继续请求,默认为false
        paginationInnerInterceptor.setOverflow(true);
        // 设置最大单页限制数量,默认500条,-1不限制
        paginationInnerInterceptor.setMaxLimit(500L);
        // 将分页插件放入
        mybatisPlusInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        return mybatisPlusInterceptor;
    }

}

4.2.3、controller 及 表单

TableController

@Controller
public class TableController {

    @Autowired
    UsersService usersService;

    @GetMapping("/dynamic_table")
    public String dynamic_table(@RequestParam(value = "pn", defaultValue = "1")Integer pn, Model model){
        //表格内容的遍历
        //List<User> users = Arrays.asList(new User("zhangsan", "123456"),
        //        new User("lisi", "123444"),
        //        new User("haha", "aaaaa"),
        //        new User("hehe ", "aaddd"));
        //model.addAttribute("users",users);


        //List<Users> list = usersService.list();
        list.forEach(System.out::println);
        //model.addAttribute("userss", list);

        // 分页查询数据
        Page<Users> usersPage = new Page<>(pn, 2);
        // 分页查询的结果
        Page<Users> page = usersService.page(usersPage, null);
        model.addAttribute("page", page);
        return "table/dynamic_table";
    }

    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn",defaultValue = "1") Integer pn,
                             RedirectAttributes ra){
        usersService.removeById(id);
        ra.addAttribute("pn", pn);
        return "redirect:/dynamic_table";
    }
}

表单

<table class="display table table-bordered table-striped" id="dynamic-table">
                                    <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>id</th>
                                        <th>name</th>
                                        <th>age</th>
                                        <th>email</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody role="alert" aria-live="polite" aria-relevant="all">
                                    <tr class="gradeX odd" th:each="users,stat:${page.records}">
                                        <td th:text="${stat.count}"></td>
                                        <td th:text="${users.id}">id</td>
                                        <td th:text="${users.name}"></td>
                                        <td th:text="${users.age}"></td>
                                        <td th:text="${users.email}"></td>
                                        <td>
                                            <a th:href="@{user/delete/{id}(id=${users.id},pn=${page.current})}" class="btn btn-danger btn-sm" type="button">删除</a>
                                        </td>
                                    </tr>
                                </table>

                                <div class="row-fluid">
                                    <div class="span6">
                                        <div class="dataTables_info" id="dynamic-table_info">
                                            当前第 [[${page.current}]] 页  总计 [[${page.pages}]] 页  共 [[${page.total}]] 条记录
                                        </div>
                                    </div>
                                    <div class="span6">
                                        <div class="dataTables_paginate paging_bootstrap pagination">
                                            <ul>
                                                <li class="prev disabled"><a href="#">← 前一页</a></li>
                                                <li th:class="num==page.current?'active':''" th:each="num:${#numbers.sequence(1,page.pages)}">
                                                    <a th:href="@{/dynamic_table(pn=${num})}">[[${num}]]</a>
                                                </li>
                                                <li class="next disabled"><a href="#">下一页 → </a></li>
                                            </ul>
                                        </div>
                                    </div>

                                </div>

Guess you like

Origin blog.csdn.net/Mr_zhangyj/article/details/124000770