spring-boot-SpringBoot与数据访问

1.JDBC

(1).导入依赖

       <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>

(2).application.yml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.15.22:3306/jdbc

 效果:

 默认是org.apache.tomcat.jdbc.pool.DataSource作为数据源

数据源的相关配置都在DataSourceProperties里面

3).自动配置原理:

 在org.springframework.boot.autoconfigure.jdbc查看

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

	@ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class)
	@ConditionalOnProperty(name = "spring.datasource.type", havingValue = "org.apache.tomcat.jdbc.pool.DataSource", matchIfMissing = true)
	static class Tomcat extends DataSourceConfiguration {

		@Bean
		@ConfigurationProperties(prefix = "spring.datasource.tomcat")

2.SpringBoot默认可以支持

org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource

3.自定义数据类型(查看源码)

/**
 * Generic DataSource configuration.
 */
@ConditionalOnMissingBean(DataSource.class) @ConditionalOnProperty(name="spring.datasource.type") staticclassGeneric{
@Bean
public DataSource dataSource(DataSourceProperties properties) { //使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
      return properties.initializeDataSourceBuilder().build();
   }
}

4)DataSourceInitializer:ApplicationListener;

 作用:

   a.run SchemaScripts();运行建表语句

   b.run SchemaScripts();运行插入数据的sql语句;

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

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

2.整合Druid数据源

  (1)导入依赖

<!--引入druid数据源-->
		<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.8</version>
		</dependency>

   2)applicaton.yml

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.15.22:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver
    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).导入数据源

//读取配置文件中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;
    }
}

3.整合mybatis

  (1)导入依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis‐spring‐boot‐starter</artifactId>
    <version>1.3.1</version>
</dependency

  步骤:

   a.配置数据源相关属性(见上一节)

   b.给数据库建表

   c.创建javaBean(此处不添代码了)

   (2)注解版

//指定这是一个操作数据库的mapper 2 @Mapper
  
  publicinterfaceDepartmentMapper{
   @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的配置规则;给容器中添加一个ConfigurationCustomizer(开启驼峰命名 例如 数据库字段是last_name javaBean

  可以是lastName)

@org.springframework.context.annotation.Configuration publicclass
   MyBatisConfig{
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){
@Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
} 
};
} 
}

  springbootApplication

package com.atguigu.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
使用MapperScan扫描所有的mapper接口,可以省去每个mapper接口加@Mapper
@MapperScan(value="com.hbsi.mapper")
@SpringBootApplication
public class SpringBoot06DataJdbcApplication {

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

(3)配置文件版(此处不做详解,只标明如何扫描配置文件)

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

更多使用参照

http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

猜你喜欢

转载自blog.csdn.net/lbqlzch/article/details/82807387