【SpringBoot】:SpringBoot整合JDBC/Druid/MyBatis/JPA


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.atguigu</groupId>
    <artifactId>spring-boot-06-data-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-06-data-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <!--引入druid-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.minidev</groupId>
            <artifactId>json-smart</artifactId>
            <version>2.2.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

一、SpringBoot整合JDBC

1、查看SpringBoot的默认数据源

1).在配置文件application.yml中配置数据源
我采用的mysql一直是8.0.18,所以导入时也是更改了版本;
这里用到datasource是org.apache.tomcat.jdbc.pool.DataSource,还有其他的datasource类,如com.zaxxer.hikari.HikariDataSource,可以查看源码

spring:
  datasource:
    username: root
    password: *********
    url: jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver

2)测试类

package com.atguigu.springboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot06DataJdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
        //org.apache.tomcat.jdbc.pool.DataSource
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

数据源的相关配置都在DataSourceProperties里面;
采用org.apache.tomcat.jdbc.pool.DataSource

2、自动建sql语句表
  1. spring.datasource下有两个属性 schme、data,其中schema为表初始化语句,data为数据初始化,默认加载schema.sql与data.sql。脚本位置可以通过spring.datasource.schema 与spring.datasource.data 来改变

  2. 在application.yml中通过spring.datasource.schema指定建表脚本的位置:
    在这里插入图片描述
    在SpringBoot1.x中, 运行建表脚本不需要配置便可之间运行,但是在SpringBoot2.x中,我们需要在配置文件中配置一下:initialization-mode: always

spring:
  datasource:
    username: root
    password: *********
    url: jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 配置自动建表脚本的位置
    schema:
     - classpath:department.sql
  1. 运行启动类之后会自动创建department这个表
3、使用JdbcTemplate查表

使用JdbcTemplate查询表中的数据:
在这里插入图片描述

@Controller
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/query")
    public Map<String,Object> map(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
        return list.get(0);
    }
}

说明:在运行主类后,会自动创建department这个表,然后在表中填入数据并保存,但是建完表以后就要将配置文件的指定建表sql脚本的配置给删除,否则再次启动主类,仍会建表,那么保存的数据就没了

#    schema:
#      - classpath:department.sql

在这里插入图片描述

二、SpringBoot整合Druid数据源

1. 引入Druid数据源的依赖
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>
2. 在配置文件中切换数据源并配置与数据源相关的属性
#连接数据库的信息
spring:
  datasource:
    username: root
    password: ********
    url: jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    #采用druid
    type: com.alibaba.druid.pool.DruidDataSource

    #下面的是一串数据源属性,一般不起作用
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#    schema:
#      - classpath:department.sql
3. 编写配置类
	@Configuration
	public class DruidConfig {
	
	    //指定加载appliction.yml文件里面的spring.datasource开头的
	    // DruidDataSource类里面的属性与appliction.yml文件里面的spring.datasource开头的对应映射
	    @ConfigurationProperties(prefix = "spring.datasource")
	    @Bean
	    public DataSource druid(){
	        return  new DruidDataSource();
	    }
	}
4. 以debug方式测试配置的数据源属性是否成功

在这里插入图片描述
注意:在运行测试类的时候报错java.lang.NoClassDefFoundError: org/apache/log4j/Priority,需要在pom.xml中导入依赖:

	<dependency>
	   <groupId>log4j</groupId>
	   <artifactId>log4j</artifactId>
	   <version>1.2.17</version>
	</dependency>
5. 配置Druid的监控
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix ="spring.datasource")
    @Bean
    public DataSource druid(){
       return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        
        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        
        return  bean;
    }
}

在这里插入图片描述

三、SpringBoot整合MyBatis

1. 配置Druid数据源

导入依赖:

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

配置数据源相关属性:

spring:
  datasource:
    username: root
    password: **********
    url: jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 启动初始化
    initialization-mode: always
#   schema:
#      - classpath:sql/department.sql
#      - classpath:sql/employee.sql

    # 切换数据源的类型
    type: com.alibaba.druid.pool.DruidDataSource
   
    # 数据源其他配置
    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,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  # 指定全局配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml

创建数据库mybatis:
在这里插入图片描述
编写数据源配置类

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix ="spring.datasource")
    @Bean
    public DataSource druid(){
       return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }

    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        
        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        
        return  bean;
    }
}
2. 配置启动时初始化的建表脚本
    # 启动时初始化的建表语句
    schema:
      # 一定要注意classpath:后面没有空格
      - classpath:sql/department.sql
      - classpath:sql/employee.sql

    # 启动初始化
    initialization-mode: always

在这里插入图片描述
运行启动类创建数据表,创建完成后就要将上面的配置删掉,以防启动时再次创建。

3. 创建JavaBean封装表的属性
@Data
public class Employee {
    private Integer id;
    private  String lastName;
    private Integer gender;
    private String email;
    private Integer dId;
}
@Data
public class Department {
    private Integer id;
    private String departmentName;
}
4. MyBatis注解版
@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

Controller层:

@RestController
public class DeptController {
    @Autowired
    DepartmentMapper departmentMapper;

	//只要传递的参数和类名一致就会自动封装
    @GetMapping("/dept")
    public Department insertDepartment(Department department){
        departmentMapper.insertDept(department);
        return department;
    }

    @GetMapping("/dept/{id}")
    public Department getDepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }
}

在这里插入图片描述
在这里插入图片描述
可以看到在插入数据时,id=null,但查询出来并不为null,可以开启主键自增功能:

 @Options(useGeneratedKeys = true,keyProperty = "id")
 @Insert("insert into department(departmentName) values(#{departmentName})")
 public int insertDept(Department department);

在这里插入图片描述

5. 配置文件版

1、在主类上加上一个注解,用于扫描映射文件的接口的包

@MapperScan("com.hh.springboot.mapper")
@SpringBootApplication
public class Springboot05DataMybatis0Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot05DataMybatis0Application.class, args);
    }
}

2、EmployeeMapper接口:

public interface EmployeeMapper {
    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);
}

3、EmployeeMapper.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.hh.springboot.mapper.EmployeeMapper">

    <select id="getEmpById" resultType="com.hh.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
    </insert>
</mapper>

4、全局配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

5、Controller层:

@RestController
public class DeptController {
    @Autowired
    EmployeeMapper employeeMapper;

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id){
        return employeeMapper.getEmpById(id);
    }
}

6、在配置文件中配置位置:

mybatis:
  # 指定全局配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml

在这里插入图片描述

四、SpringBoot整合JPA

1、application.properties

spring:
  datasource:
    username: root
    password: *******
    url: jdbc:mysql://localhost:3306/jpa?serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      #     更新或者创建数据表结构
      ddl-auto: update
    #    控制台显示SQL
    show-sql: true

2、UserRepository

//完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {

}

3、User
@Entity说明这个class是实体类,并且使用默认的orm规则,即class名即数据库表中表名,class字段名即表中的字段名
如果想改变这种默认的orm规则,就要使用@Table来改变class名与数据库中表名的映射规则,@Column来改变class中字段名与db中表的字段名的映射规则

[@Entity]  
   必须与@Id注解 结合使用  
     否则  No identifier specified for entity:   
   name 属性  
    (可选)实体名称。 缺省为实体类的非限定名称。   
        该名称用于引用查询中的实体。  
        该名称不能是Java持久性查询语言中的保留字面值。  
   
   不与@Table结合的话 表名 默认为 SnakeCaseStrategy(命名策略 )为表名  
    若使用 name属性 且没有与@Table结合 则表名为 name值的SnakeCaseStrategy(命名策略 )  
    例如:  
        @Entity  
            public class UserEntity{...} 表名 user_entity  
        @Entity(name="UE")  
            public class UserEntity{...} 表名 ue  
        @Entity(name="UsEntity")  
            public class UserEntity{...} 表名 us_entity  

@Entity//告诉JPA这是一个实体类(和数据库表映射的类)
@Table//指定和那个数据库表对应,如果省略就是类名小写
@Data
@JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" })
public class User implements Serializable {
    @Id//表明这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//这是一个自增主键
    private Integer id;
    @Column//这是和数据库表对应的一个列
    private String lastName;
    @Column//省略列名就是属性名
    private String email;
}

4、UserController

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id")Integer id){
        User user = userRepository.getOne(id);
        return user;
    }

    @GetMapping("/user")
    public User insertUser(User user){
        User save = userRepository.save(user);
        return save;
    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
完整版:https://download.csdn.net/download/qq_27595745/89522468 【课程大纲】 1-1 什么是java 1-2 认识java语言 1-3 java平台的体系结构 1-4 java SE环境安装和配置 2-1 java程序简介 2-2 计算机中的程序 2-3 java程序 2-4 java类库组织结构和文档 2-5 java虚拟机简介 2-6 java的垃圾回收器 2-7 java上机练习 3-1 java语言基础入门 3-2 数据的分类 3-3 标识符、关键字和常量 3-4 运算符 3-5 表达式 3-6 顺序结构和选择结构 3-7 循环语句 3-8 跳转语句 3-9 MyEclipse工具介绍 3-10 java基础知识章节练习 4-1 一维数组 4-2 数组应用 4-3 多维数组 4-4 排序算法 4-5 增强for循环 4-6 数组和排序算法章节练习 5-0 抽象和封装 5-1 面向过程的设计思想 5-2 面向对象的设计思想 5-3 抽象 5-4 封装 5-5 属性 5-6 方法的定义 5-7 this关键字 5-8 javaBean 5-9 包 package 5-10 抽象和封装章节练习 6-0 继承和多态 6-1 继承 6-2 object类 6-3 多态 6-4 访问修饰符 6-5 static修饰符 6-6 final修饰符 6-7 abstract修饰符 6-8 接口 6-9 继承和多态 章节练习 7-1 面向对象的分析与设计简介 7-2 对象模型建立 7-3 类之间的关系 7-4 软件的可维护与复用设计原则 7-5 面向对象的设计与分析 章节练习 8-1 内部类与包装器 8-2 对象包装器 8-3 装箱和拆箱 8-4 练习题 9-1 常用类介绍 9-2 StringBuffer和String Builder类 9-3 Rintime类的使用 9-4 日期类简介 9-5 java程序国际化的实现 9-6 Random类和Math类 9-7 枚举 9-8 练习题 10-1 java异常处理 10-2 认识异常 10-3 使用try和catch捕获异常 10-4 使用throw和throws引发异常 10-5 finally关键字 10-6 getMessage和printStackTrace方法 10-7 异常分类 10-8 自定义异常类 10-9 练习题 11-1 Java集合框架和泛型机制 11-2 Collection接口 11-3 Set接口实现类 11-4 List接口实现类 11-5 Map接口 11-6 Collections类 11-7 泛型概述 11-8 练习题 12-1 多线程 12-2 线程的生命周期 12-3 线程的调度和优先级 12-4 线程的同步 12-5 集合类的同步问题 12-6 用Timer类调度任务 12-7 练习题 13-1 Java IO 13-2 Java IO原理 13-3 流类的结构 13-4 文件流 13-5 缓冲流 13-6 转换流 13-7 数据流 13-8 打印流 13-9 对象流 13-10 随机存取文件流 13-11 zip文件流 13-12 练习题 14-1 图形用户界面设计 14-2 事件处理机制 14-3 AWT常用组件 14-4 swing简介 14-5 可视化开发swing组件 14-6 声音的播放和处理 14-7 2D图形的绘制 14-8 练习题 15-1 反射 15-2 使用Java反射机制 15-3 反射与动态代理 15-4 练习题 16-1 Java标注 16-2 JDK内置的基本标注类型 16-3 自定义标注类型 16-4 对标注进行标注 16-5 利用反射获取标注信息 16-6 练习题 17-1 顶目实战1-单机版五子棋游戏 17-2 总体设计 17-3 代码实现 17-4 程序的运行与发布 17-5 手动生成可执行JAR文件 17-6 练习题 18-1 Java数据库编程 18-2 JDBC类和接口 18-3 JDBC操作SQL 18-4 JDBC基本示例 18-5 JDBC应用示例 18-6 练习题 19-1 。。。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值