SpringBoot与数据访问

SpringBoot与数据访问

一、JDBC

  • 使用Idea 集成开发工具搭建

image-20200914092829685

  • pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
  • 使用yml配置文件进行配置
spring:
  datasource:
    username: root
    password: 1234
    url: jdbc:mysql://192.168.64.129:3307/jdbc?characterEncoding=UTF-8&serverTimezone=UTC
    #如果使用mysql 8.0.20及以上需要指定时区 使用com.mysql.cj.jdbc.Driver,低版本的只需要把cj去掉即可
    driver-class-name: com.mysql.cj.jdbc.Driver
    #指定使用哪个数据源,结合自己的情况而定
    #type: com.alibaba.druid.pool.DruidDataSource

效果

​ 1. 默认使用 com.zaxxer.hikari.HikariDataSource 作为数据源(springBoot的版本为:2.3.3);

//查看DataSourceAutoConfiguration中的方法
    @Configuration
    @Conditional(PooledDataSourceCondition.class)
    @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
    @Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
            DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.Generic.class,
            DataSourceJmxConfiguration.class })
    protected static class PooledDataSourceConfiguration {
    }
  1. springboot 1.5.10版本 默认是使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源;

    配置源的相关配置都在DataSourceProperties里面;

    自动配置原理:

    org.springframework.boot.autoconfigure.jdbc ;

    1. 参考DataSurceConfiguration,根据配置创建数据源,默认使用Tomcat连接池;可以使用spring.datasource.type指定自定义的数据源类型‘

    2)SpringBoot默认可以支持:

    org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource
    
    1. 自定义数据源类型
    /**
    * Generic DataSource configuration.
    */
    @ConditionalOnMissingBean(DataSource.class)
    @ConditionalOnProperty(name = "spring.datasource.type")
    static class Generic {
        @Bean
    	public DataSource dataSource(DataSourceProperties properties) {
    		//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
    		return properties.initializeDataSourceBuilder().build();
    	}
    }
    

    4) DataSourceInitialzerApplicationListener

    作用 :

    ​ ① runSchemaScripts(); 运行建表语句;

    ​ ② runDataScripts():运行插入的sql语句;

    默认只需要将文件命名为:

    schema-*.sql、data-*.sql
    默认规则: schema.sql , schema-all.sql
    可是使用
    	schema:
    	 - classpath:department.sql
    	 指定位置
    

    注意:SpringBoot 2.x及以需要配置

    具体的参考我这篇博客详细介绍了

    spring.datasource.initialization-mode=always
    
    

    否则不会自动创建sql语句

    5)操作数据库:自动配置jdbcTemplate操作数据库

二、整合Driuid 数据源

​ pom.xml 导入依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.21</version>
</dependency>
① 添加基本配置

​ 不使用默认的配置,使用自己的配置

   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

【DruidConfig.java】

@Configuration
public class DruidConfig {

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

使用在测试类中启动DegBug启动

@SpringBootTest
class SpringBoot06DateJdbcApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        // com.zaxxer.hikari.HikariDataSource
        System.out.println(dataSource.getClass());

        System.out.println("*********************");
        Connection conn = dataSource.getConnection();
        System.out.println(conn);
        conn.close();
    }
}

启动

image-20200914152433864

​ Debug启动出现异常,原因分析:应该在运行中缺少log4j的依赖,导致无法启动。

解决方法

// 在pom.xml 文件中导入log4j的依赖
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

启动配置生效

image-20200914152951350

② 整合Druid 数据源

【DruidConfig.java】

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

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

        bean.setInitParameters(initParams);
        return bean;
    }

    /**
     * 配置一个web监控的filter
     *
     */
    @Bean
    public FilterRegistrationBean webStratFilert(){
        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;
    }

【HelloController.java】

@Controller
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;

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

测试

image-20200914160529461

image-20200914160647526

image-20200914160845585

三、 整合Mybatis

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

image-20200914163633256

准备步骤

  1. 配置数据源相关属性
spring:
  datasource:
    #   数据源基本配置
    username: root
    password: 6090
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.64.129:3307/mybatis
    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
    # 配置自动执行sql语句
    initialization-mode: always
  1. 给数据库建表

    在yml配置文件中添加

    schema:
      - classpath:sql/department.sql
      - classpath:sql/employee.sql

image-20200914165759599

  1. 创建javabean
public class Employee {
    private Integer id;
    private String lastName;
    private Integer gender;
    private String  email;
    private Integer dId;
    
    //生成相应的get、set方法
} 

public class Department {
    private Integer id;
    private String departmenName;
    // 生成相应的get、set方法
}    
① 注解版

【DepartmentMapper.java】

@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id = #{id}")

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

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

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

【DeptController.java】

@RestController
public class DeptController {

    @Autowired
    DepartmentMapper departmentMapper;

    @GetMapping(value = "/dept/{id}")
    public Department getdepartment(@PathVariable("id") Integer id){
        return departmentMapper.getDeptById(id);
    }
    
    @GetMapping(value = "/dept")
    public Department insertDept(Department department){
        departmentMapper.insertDept(department);
        return department;
    }
}

测试:

image-20200914174351188

​ 出现异常,获取值不完整,原因分析departmentName这个属性名跟数据库的字段不一致,可以自定义增加驼峰命名来解决这个问题

@Configuration
public class MybatisConfig {

    /**
     *  自定义配置驼峰命名规则
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
       return new ConfigurationCustomizer() {
           @Override
           public void customize(org.apache.ibatis.session.Configuration configuration) {
               configuration.setMapUnderscoreToCamelCase(true);
           }
       };
    }
}

image-20200914175207784

image-20200914203032279

image-20200914203054898

补充:使用MapperScan批量扫描所有的Mapper接口

@MapperScan(value = "com.oy.springboot06.Mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
    }
}
② 配置文件版
  • 在配置yml文件中配置
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件位置

【EmployeeMapper.class】

@Mapper
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

【DeptController.java】

@RestController
public class DeptController {

    @Autowired
    EmployeeMapper employeeMapper;

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

}
  • 结构图

image-20200914210243433

【mybatis-config.xml】配置驼峰命名规则

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

测试

image-20200914210430916

更多使用参照:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

四、整合SpringData JPA

① SpringData简介

image-20200915093030170

② 整合SpringData JPA

JPA : ORM(Object Relational Mapping)

  1. 编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
/**
*@Description 使用JPA注解配置映射关系
*@Author OY
*@Date 2020/9/15
*@Time 9:55
*/
@Entity // 告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和那个数据表对应;如果省略默认表民就是user
public class User {

    @Id // 这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)// 自增主键
    private Integer id;

    @Column(name = "last_name", length = 50) // 这是和数据表对应的一个列
    private String lastName;

    @Column // 省略默认的列名就是属性名
    private String email;
    
    // 省略get.set方法。。。。
}    
  1. 编写一个Dao接口来操作实体类对应的数据表(Repository)
/**
*@Description 继承JpaRepository来完成对数据库的操作
*@Author OY
*@Date 2020/9/15
*@Time 10:12
*/
public interface UserRepository extends JpaRepository<User, Integer> {
}
  1. 基本配置JpaProperties(yml中)
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.64.129:3307/jpa
    driver-class-name: com.mysql.cj.jdbc.Driver
    initialization-mode: always
  jpa:
    hibernate:
# 更新或者创建数据表结构
      ddl-auto: update
# 控制台显示SQL
    show-sql: true

4.测试

【UserController.java】

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        Example<User> example = Example.of(user);
        Optional<User> one = userRepository.findOne(example);
        return one.get();

    }

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

    @GetMapping("/user/all")
    public List<User> getAll(){
        List<User> all = userRepository.findAll();
        return all;
    }
}

image-20200915105830491

image-20200915105905849
image-20200915105953515

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值