8.10 数据源整合

配置数据源

在配置文件中写好,username,password,url,Driver后,就可以直接连接数据库

@Autowired

DateSource dataSource;

SpringBoot中有很多xxxxTemplate,比如jdbcTemplate,redisTemplate等模板,可以直接拿来即用

jdbctemplate

jdbctemplate是spring自带的,功能比较简单

  1. 导入依赖
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>  
  1. 配置数据库

    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/powernode?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT&allowPublicKeyRetrieval=true
    spring.datasource.username=root
    spring.datasource.password=admin
    
  2. 创建JdbcTemplate类,通过JdbcTemplate执行sql语句。

整合Druid连接池:

在pom文件中添加依赖

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

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
</dependency>

在application中添加配置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wrZh5n1B-1628604336793)(D:\Typora\记录\image-20210524223416589.png)]

spring:
  datasource:
    username: root
    password: admin
    url: jdbc:mysql://localhost:3306/springstudy4?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    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

添加Druid配置文件

@Configuration
public class DruidConfig {

    //数据源的使用
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource DruidDataSource(){
        return new DruidDataSource();
    }

    //后台监控:相当于web.xml
    //因为springboot内置了servlet容器,所以没有web.xml,用ServletRegistrationBean替代了web.xml
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

        HashMap<String,String> initParameters=new HashMap<>();

        //增加配置
        initParameters.put("loginUsername","root");//登录key是固定的 loginUsername  loginPassword
        initParameters.put("loginPassword","admin");

        //设置谁可以访问
        initParameters.put("allow","");

        //禁止谁可以访问
        //initParameters.put("hs","192.168.1.1");

        bean.setInitParameters(initParameters);
        return bean;
    }


    //配置拦截器
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean=new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        //这些东西不进行统计
        Map<String,String> initParameters=new HashMap<>();
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        return bean;
    }
}

只要在配置文件中写了

type: com.alibaba.druid.pool.DruidDataSource

项目连接池就变成了Druid

整合mybatis:

1.使用xml文件方式

1.添加依赖

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

2.建立UserMapper接口

​ 开启自动扫描方法:

​ 方法1:Springboot启动类上添加注解@MapperScan(“com.hs.mapper”)

​ 方法2:在Mapper接口上添加@Mapper

3.在resources下新建一个目录mybatis,在mybatis下新建一个目录mapper,在mapper目录中新建对应的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.hs.backstage.mapper.UserMapper">

4.在配置文件中添加相关配置

#整合mybatis
#设置实体类的别名
mybatis.type-aliases-package=com.hs.springbootstudy5_mybatis.domain
#设置mapper配置文件所在的位置 classpath后不需要/
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
#开启驼峰命名,即自动将mysql中的hs_a转化为hsA
mybatis.configuration.map-underscore-to-camel-case=true
2.使用全注解方式

同样添加依赖,并在配置文件中配置

只是建立Mapper接口时有所不同

@Mapper
public interface UserMapper {
    @Select("select ename userName,job password from emp where empno=#{id}")
    public User getUser(Long id);
}

xml文件方式和注解方式可以混合使用。但是如果一个方法使用了注解方式,那么xml文件中就不能有这个方法

整合mybatis-plus

  1. 引入依赖
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

mybatis-plus中包含mybatis,引入Mybatis-plus后不需要再引入mybatis

  • mapperLocations XML文件路径是自动配置好的。默认值为classpath*:/mapper/**/*.xml;

    包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下

  1. 编写Mapper接口,只要写一个Mapper接口继承BaseMapper<要操作的实体类>,并且在这个接口上添加@Mapper就可以了

  2. 编写service接口及service实现类;service接口需要继承IService< T>,实现类需要继承ServiceImpl<M,T> ,并继承service接口

mybatisplus的注解
  • @TableName(“xxx”) 在实体类上添加,指定数据库中对应的表名,不加默认为类名
  • @TableId(“xxx”) 在属性上添加,指定主键 有一个type属性用来指定主键类型:AUTO 数据库ID自增;INPUT insert前自行set主键值;
  • @TableField(“xxx”) 加在属性上,指定数据库中对应的属性名
  • @Version 乐观锁注解、标记 @Verison 在字段上
mybatisplus的配置
mybatis-plus:
  configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志
mybatisplus分页
  1. MP中有一个Page类用于分页
Page<Teacher> page = new Page<>(pn, 2);//按页查询数据
//分页查询结果,包含当前页码、查询结果、总页码数等等
Page<Teacher> page1 = teacherService.page(page,null);
model.addAttribute("teacherpage",page1);
List<Teacher> records = page1.getRecords();//获取结果中的teachers信息
long current = page1.getCurrent();//获取当前页码
  1. 还需要添加分页配置类才能使第 1 步中的分页代码生效
@Configuration
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        //这是分页拦截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.H2);
        paginationInnerInterceptor.setMaxLimit(500L);//设置每页最大条数
        paginationInnerInterceptor.setOverflow(true);//当查询到末位时是否循环
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }
}
thymeleaf中分页所需代码:
<li th:class="${num==user.current}?'active':''">如果页码num等于当前页码,就让这个页码常亮
th:each="num:${#numbers.sequence(1,users.pages)}"生成1到users.pages的数列
th:href="@{/dynamic_table(pn=${num})} 动态添加参数 结果为/dynamic_table?pn=xxx
    
    
<li th:class="${teacherpage.current==num?'active':''}" th:each="num:${#numbers.sequence(1,teacherpage.pages)}">
		<a th:href="@{/dynamic_table(pn=${num})}">[[${num}]]</a><a href="#">[[${num}]]</a>
</li>
请求转发时携带参数:
public String dynamicTable(@RequestParam(value = "pn",defaultValue = "1") Integer pn,
                               Model model,
                               RedirectAttributes re)
{
    re.addAttribute("pn",1);//重定向也能带参数pn,值为1
    return "redirect:main";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值