码迷,mamicode.com
首页 > 编程语言 > 详细

(六)SpringBoot与数据访问

时间:2018-08-13 00:46:20      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:group   绑定   dmi   init   自动   .config   min   映射文件   font   

1、JDBC

 

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

 

1 spring:
2   datasource:
3     username: root
4     password: 123456
5     url: jdbc:mysql://192.168.1.104:3306/jdbc
6     driver-class-name: com.mysql.jdbc.Driver

效果:

  默认使用org.apache.tomcat.jdbc.pool.DataSource作为数据源;

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

自动配置原理:

org.springframework.boot.autoconfigure.jdbc:

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

2、SpringBoot默认可以支持;

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

3、自定义数据源类型

/**
* 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、DataSourceInitializer:ApplicationListener

  作用:

    1)、runSchemaScripts();运行建表语句;

       2)、runDataScripts();运行插入数据的sql语句;

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

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

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

2、整合Druid数据源

导入Druid数据源

 1 @Configuration
 2 public class DruidConfig {
 3 
 4     @ConfigurationProperties(prefix = "spring.datasource")
 5     @Bean
 6     public DataSource druid(){
 7         return new DruidDataSource();
 8     }
 9 
10     //配置Druid的监控
11     //1、配置一个管理后台的Servlet
12     @Bean
13     public ServletRegistrationBean statViewServlet(){
14         ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
15         Map<String,String> initParams = new HashMap<>();
16         initParams.put("loginUsername","admin");
17         initParams.put("loginPassword","123456");
18         initParams.put("allow","");//默认允许所有访问
19         initParams.put("deny","192.168.1.102");
20         bean.setInitParameters(initParams);
21         return bean;
22     }
23 
24     //2、配置一个web监控的filter
25     @Bean
26     public FilterRegistrationBean webStatFilter(){
27         FilterRegistrationBean bean = new FilterRegistrationBean();
28         bean.setFilter(new WebStatFilter());
29         Map<String,String> initParams = new HashMap<>();
30         initParams.put("exclusions","*.js,*.css,/druid/*");
31         bean.setInitParameters(initParams);
32         bean.setUrlPatterns(Arrays.asList("/*"));
33         return bean;
34     }
35 
36 }

3、整合Mybatis

1 <dependency>
2     <groupId>org.mybatis.spring.boot</groupId>
3     <artifactId>mybatis-spring-boot-starter</artifactId>
4     <version>1.3.2</version>
5 </dependency>

技术分享图片

 

步骤:

  1)、配置数据源相关属性(见上一节Druid)

  2)、给数据库建表

  3)、创建JavaBean

4、注解版

//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    Department getDeptById(Integer id);

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

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

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

}

问题:

自定义MyBatis的配置规则,给容器中添加一个ConfigurationCustomizer;

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }

}

 

使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.young.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

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

 

5、配置文件版

 

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

 

(六)SpringBoot与数据访问

标签:group   绑定   dmi   init   自动   .config   min   映射文件   font   

原文地址:https://www.cnblogs.com/yang-young-young/p/9465497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!