(六)SpringBoot與數據訪問

一、JDBCcss

 

<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

效果:java

  默認使用org.apache.tomcat.jdbc.pool.DataSource做爲數據源;mysql

  數據源的相關配置都在DataSourceProperties裏面;web

自動配置原理:spring

org.springframework.boot.autoconfigure.jdbc:sql

一、參考DataSourceConfiguration,根據配置建立數據源,默認使用Tomcat鏈接池;能夠使用spring.datasource.type指定自定義的數據源類型;數據庫

二、SpringBoot默承認以支持;apache

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

三、自定義數據源類型tomcat

/**
* 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();
    }

}

四、DataSourceInitializer:ApplicationListenerspringboot

  做用:

    1)、runSchemaScripts();運行建表語句;

       2)、runDataScripts();運行插入數據的sql語句;

默認只須要將文件命名爲:

schema-*.sql、data-*.sql
默認規則:schema.sql,schema-all.sql;
能夠使用   
    schema:
      - classpath:department.sql
      指定位置

五、操做數據庫:自動配置jdbcTemplate操做數據庫

二、整合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     //一、配置一個管理後臺的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     //二、配置一個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 }

三、整合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

1)、註解版

//指定這是一個操做數據庫的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);
    }
}

 

2)、配置文件版

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

 

四、整合SpringData JPA

1)、SpringData簡介

 

2)、整合SpringData JPA

JPA:ORM(Object Relational Mapping)對象關係映射

1)、編寫一個實體類(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;

 

2)、編寫一個Dao接口來操做實體類對應的數據表(Repository)

//繼承JpaRepository來完成對數據庫的操做
public interface UserRepository extends JpaRepository<User,Integer>{
}

3)、基本的配置

spring:
  jpa:
    hibernate:
#     更新或者建立數據表結構
      ddl-auto: update
#   控制檯顯示SQL
    show-sql: true
相關文章
相關標籤/搜索