Six Springboot and data access

Source: Internet
Author: User

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:root4    password:1234565      url:jdbc:mysql://192.168.1.104:3306/jdbc6     driver-class-name: Com.mysql.jdbc.Driver

Effect:

Use Org.apache.tomcat.jdbc.pool.DataSource as the data source by default;

The relevant configuration of the data source is inside the datasourceproperties;

Automatic Configuration principle:

ORG.SPRINGFRAMEWORK.BOOT.AUTOCONFIGURE.JDBC:

1, reference datasourceconfiguration, according to the configuration to create a data source, the default use of Tomcat connection pool; You can use Spring.datasource.type to specify a custom data source type;

2, springboot default can support;

Org.apache.tomcat.jdbc.pool.DataSource, Hikaridatasource, Basicdatasource

3. Custom data Source Type

 /**  * Generic DataSource configuration.  */  @ConditionalOnMissingBean (DataSource.  class  ) @ConditionalOnProperty (name  = "Spring.datasource.type" )  static   Class   Generic {@Bean  public   DataSource DataSource (Datasourceproperties properties) {    use Datasourcebuilder to create a data source, use reflection to create a data source that responds to type, and bind related properties  return   Properties.initializedatasourcebuilder (). build (); }}

4. Datasourceinitializer: Applicationlistener

Role:

1),runschemascripts (); Run the build table statement;

2), rundatascripts (); Run the SQL statement that inserts the data;

By default, you only need to name the file:

Schema-*.sql, data-*.sql default rule: schema.sql,schema-all.sql; You can use       Schema:      -classpath:department.sql      Specify location

5. Operation database: Automatic configuration JdbcTemplate Operation database

2. Integrate Druid Data source

Importing Druid data sources

1 @Configuration2  Public classDruidconfig {3 4@ConfigurationProperties (prefix = "Spring.datasource")5 @Bean6      PublicDataSource Druid () {7         return NewDruiddatasource ();8     }9 Ten     //Configuring monitoring for Druid One     //1. Configure a servlet that manages the background A @Bean -      PublicServletregistrationbean Statviewservlet () { -Servletregistrationbean Bean =NewServletregistrationbean (NewStatviewservlet (), "/druid/*"); theMap<string,string> InitParams =NewHashmap<>(); -Initparams.put ("Loginusername", "admin"); -Initparams.put ("Loginpassword", "123456"); -Initparams.put ("Allow", "");//All access is allowed by default +Initparams.put ("Deny", "192.168.1.102"); - bean.setinitparameters (initparams); +         returnBean; A     } at  -     //2. Configure a Web monitoring filter - @Bean -      PublicFilterregistrationbean Webstatfilter () { -Filterregistrationbean Bean =NewFilterregistrationbean (); -Bean.setfilter (NewWebstatfilter ()); inMap<string,string> InitParams =NewHashmap<>(); -Initparams.put ("Exclusions", "*.js,*.css,/druid/*"); to bean.setinitparameters (initparams); +Bean.seturlpatterns (Arrays.aslist ("/*")); -         returnBean; the     } *  $}

3, integrated 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>

Steps:

1), configure Data source related properties (see previous section Druid)

2), create a table for the database

3), create JavaBean

4. Annotated version

//Specifies that this is a mapper of an operational database@Mapper Public Interfacedepartmentmapper {@Select ("SELECT * from department where Id=#{id}") Department Getdeptbyid (Integer ID); @Delete ("Delete from department where Id=#{id}")    intDeletedeptbyid (Integer ID); @Options (Usegeneratedkeys=true, Keyproperty = "id") @Insert ("INSERT into department (departmentname) VALUES (#{departmentname})")    intinsertdept (Department Department); @Update ("Update department set Departmentname=#{departmentname} where Id=#{id}")    intupdatedept (Department Department);}

Problem:

Custom MyBatis configuration rules, add a configurationcustomizer to the container;

@org. Springframework.context.annotation.Configuration  Public class mybatisconfig {    @Bean    public  configurationcustomizer Configurationcustomizer () {         return New Configurationcustomizer () {            @Override            publicvoid  Customize ( Configuration configuration) {                configuration.setmapunderscoretocamelcase (true);            }        };    }}

= "Com.young.springboot.mapper") @SpringBootApplicationpublicclass  springboot06datamybatisapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (springboot06datamybatisapplication). class , args);}    }

5. Configuration file version

MyBatis:  config-location:classpath:mybatis/mybatis-config.xml Specifies the location of the global configuration file  Mapper-locations:classpath: Mybatis/mapper/*.xml  specifying the location of the SQL mapping file

Six Springboot and data access

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.