Spring Boot系列笔记--数据访问

一、JDBC

  • SpringBoot使用JDBC只需导入相应依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
  • sqlName.sql放入resources文件夹内,再在application.yml中配置必要属性,classpath:后没有空格
    spring:
      datasource:
        username: root
        password: password
        url: jdbc:mysql://ip address:3306/database
        driver-class-name: com.mysql.cj.jdbc.Driver
        # 需要执行的建表语句,
        schema:
          - calsspath:sqlName.sql
    	#Spring Boot2.x 必须添加 initialization-mode配置才会执行建表语句
    	initialization-mode: always
    
  • 这样即可将DataSource默认数据源放入容器中

二、整合Druid数据源

  • application.yml中配置Druid数据源
    spring:
      datasource:
    #   数据源基本配置
        username: root
        password: password
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://ip address:3306/database
        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
    
  • 需要写一个配置类
    package com.atguigu.springboot.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import com.alibaba.druid.support.http.WebStatFilter;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.sql.DataSource;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    @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", "123");
            initParams.put("allow","");//默认就是允许所有访问
            initParams.put("deny","ip address");
            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;
        }
    }
    
  • 访问http://localhost:8080/druid/login.html会进入一个监控页面

三、整合Mybatis

1. 使用注解配置相关类

  • 创建数据库、表、JavaBean以及配置数据源相关属性
  • 创建操作数据库的mapper类
    @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);
    
        @Options(useGeneratedKeys = true,keyProperty = "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);
    }
    
  • 自定义Mybatis的配置规则
    @Configuration
    public class MybatisConfig {
          
          
    
        @Bean
        public ConfigurationCustomizer customizer(){
          
          
            return new ConfigurationCustomizer() {
          
          
                @Override
                public void customize(org.apache.ibatis.session.Configuration configuration) {
          
          
                	//驼峰命名
                    configuration.setMapUnderscoreToCamelCase(true);
                }
            };
        }
    }
    
  • 当mapper数量过多,配置@Mapper注解麻烦,使用@MapperScan批量扫描所有的Mapper接口
    @MapperScan(value = "com.atguigu.springboot.mapper")
    @SpringBootApplication
    public class SpringBoot06DataMybatisApplication {
          
          
    
    	public static void main(String[] args) {
          
          
    		SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
    	}
    }
    

2. 使用配置文件

  • application.yml中添加配置
    mybatis:
      config-location: classpath:mybatis/mybatis-config.xml #指定全局配置文件的位置
      mapper-locations: classpath:mybatis/mapper/*.xml  #指定sql映射文件的位置
    
  • SQL映射文件
    <?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.atguigu.springboot.mapper.EmployeeMapper">
        <select id="getEmpById" resultType="com.atguigu.springboot.bean.Employee">
            select * from employee where id = #{id}
      </select>
    </mapper>
    
  • 全局配置文件
    <?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>
    

四、整合SpringData JPA

  • 编写一个bean,和数据表进行映射
    //使用JPA注解配置映射关系
    @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;
    }    
    
  • 编写一个Dao接口来操作实体类对应的数据表(Repository)
    //继承JpaRepository来完成对数据库的操作
    public interface UserRepository extends JpaRepository<User,Integer> {
          
          
    }
    
  • 基本的配置JpaProperties
    spring:  
     jpa:
        hibernate:
    #     更新或者创建数据表结构
          ddl-auto: update
    #    控制台显示SQL
        show-sql: true
    

猜你喜欢

转载自blog.csdn.net/weixin_44863537/article/details/109125857