Writing in the front

In view of the message that someone wants to learn SpringBoot related knowledge, I am going to write a related blog about SpringBoot series, the goal is to let students read this series of blog posts, can have a glimpse of SpringBoot. This preliminary set down a series of blog posts including SpringBoot introduction, introduction, configuration, log, web development, data access, combined with related docker, caching, message queue, retrieve, tasks, security, distributed and so on a series of blog posts, a lot of work, is a long process, every step I have detailed as far as possible, deserve to go up screenshot shows, I hope it’s really useful for those of you who are watching. I just want to share technical blog posts, but also want to say that if you think it is useful, please click on the following, give a like, also a relief to me, after all, I have to lose a lot of hair, hey hey hey

Serial article transport bar

Detailed SpringBoot tutorial introduction (1) detailed SpringBoot tutorial introduction (2) detailed SpringBoot tutorial configuration file (1) detailed SpringBoot tutorial configuration file (2) detailed SpringBoot tutorial log framework Detailed SpringBoot tutorial Web development (1) detailed SpringBoot tutorial Web development (2) detailed SpringBoot tutorial Web development (3) detailed SpringBoot tutorial data access detailed SpringBoot tutorial boot configuration principle Detailed SpringBoot tutorial for cache development

SpringBoot and data access

For the Data access layer, whether SQL or NOSQL, SpringBoot by default uses the integration of Spring Data for unified processing, adding a lot of automatic configuration, masking a lot of Settings. SpringBoot introduces xxxTemplates and xxxRepositories to simplify operations on the data access layer (using SpringBoot’s JPA approach, which is very convenient, as explained below). For us, it’s a simple setup. We will test using SQL correlation in the data access section. Next we’ll show you how SpringBoot uses the following three data access methods

  • JDBC
  • MyBatis
  • JPA

JDBC is used in SpringBoot

In fact, JDBC is more primitive database access, but have to say, a lot of things are based on it to encapsulate, and there are a lot of projects like using JDBC, so when we learn, or need to understand JDBC related, but here we force JDBC principle to explain, Since we are beyond the scope of this blog post, we will only talk about how to use JDBC. Using JDBC in SpringBoot is very simple. Here we use the Idea wizard to create a new project. When checking dependencies, we check mysql Dirver and JDBC in addition to checking web modules as usual



After creating the project, the pom.xml package will look something like this. Of course, you can also create a Maven project and import dependencies in this way



Once the project is created, how do we use it? It is very simple, we just need to do some configuration in the main configuration file, such as the database account password, here to say that we use mysql relational database, as follows



We can write the following code to test in the test class to see if the connection is successful. If the connection is not successful, an error will be reported. If it runs normally, the connection is successful.



Here we can see the console output log, we can know that SpringBoot default to be class com. Zaxxer. Hikari. HikariDataSource as data source, and the relevant configuration in DataSourceProperties are data source.

If we create SQL directly under Resources and do not configure it in any configuration file, we need to name the SQL specifically to make it effective. Of course, we usually configure the SQL in the main configuration file, as follows

Schema - *. SQL, data - *. SQL
Default rules: schema. SQL, schema-all. SQL;
You can use   
	schema:
      - classpath:department.sql
      The specified location
Copy the code

Principle of Automatic configuration

First of all, by convention, or find the JDBC automatic configuration, and then by looking at automatic configuration class is analyzed, and JDBC automatic configuration class is org. Springframework. Boot. Autoconfigure. JDBC

We can refer to a DataSourceConfiguration uration to create a datasource based on the configuration, using a hikari connection pool by default, where we can specify a custom datasource type using spring.datasource.type.

It is important to note that SpringBoot supports the following data sources by default. Previously, Tomcat was used as the default data source in SpringBoot1.x, while Hikari is used as the data source in SpringBoot 2.x

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

Of course, since we have a default data source, we can certainly customize the data source type

/** * Generic DataSource configuration. */
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {

   @Bean
   public DataSource dataSource(DataSourceProperties properties) {
       // Use the DataSourceBuilder to create the data source, use reflection to create the data source for the response type, and bind the related properties
      returnproperties.initializeDataSourceBuilder().build(); }}Copy the code

Integrate Druid data sources

The default Hikari data source for SpringBoot is Hikari, and the default Hikari data source for SpringBoot is Hikari. The default Hikari data source is Hikari, and the default Hikari data source is Hikari. But it feels longer)



I first imported the Druid data source into my project, and then created a configuration class in the Config directory to control Druid. I tested the configuration class as follows, using filters and listeners as examples


@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(a){
       return  new DruidDataSource();
    }

    // Configure Druid monitoring
    // configure a Servlet to manage the background
    @Bean
    public ServletRegistrationBean statViewServlet(a){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername"."admin");
        initParams.put("loginPassword"."123456");
        initParams.put("allow"."");// All access is allowed by default
        initParams.put("deny"."192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2. Configure a filter for web monitoring
    @Bean
    public FilterRegistrationBean webStatFilter(a){
        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("/ *"));

        returnbean; }}Copy the code

MyBatis SpringBoot integration

The first step is of course to import the dependency of MyBatis, which is as follows

<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> The < version > 2.1.1 < / version > < / dependency >Copy the code

Use steps:

  • Configure data source attributes

  • Create tables for the database
  • Create a JavaBean

How to use Mybatis with annotations

First create a Mapper package under SRC, then create the mapper interface for the corresponding entity under the package, as shown below

// Specify that this is a mapper that operates on a database
@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);
}
Copy the code

SpringBoot has a custom configuration rule for MyBatis. Add a ConfigurationCustomizer to the container, and use MapperScan to batch scan all Mapper interfaces.

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

    @Bean
    public ConfigurationCustomizer configurationCustomizer(a){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true); }}; }}Copy the code
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

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

Using configuration files

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml Specify the location of the global configuration file
  mapper-locations: classpath:mybatis/mapper/*.xml  Specify the location of the SQL mapping file
Copy the code

Refer to Mybatis’ official documentation for SpringBoot for more usage

SpringBoot integrates the SpringData JPA

SpringData provides us with a unified API for manipulating the data access layer; This is primarily done by the Spring Data Commons project. Spring Data Commons allows us to use both relational and non-relational Data access technologies based on a unified Spring standard that includes CRUD (Create, get, update, delete), query, sort, and paging operations.



SpringDataJPA has a Repository interface such as Repository<T, ID extends Serializable> RevisionRepository<T, ID extends Serializable, N extends Number & Comparable> Basic CRUD operations, PagingAndSortingRepository ID extends the Serializable > < T, ID extends the Serializable > : basic CRUD and paging

Integrated SpringData JPA

Once we introduce our dependencies, we can write an entity class (bean) to map to the table and configure the mapping.

// Configure the mapping using JPA annotations
@Entity // Tell JPA that this is an entity class (and a table mapping class)
@Table(name = "tbl_user") // @table to specify the corresponding Table; User if the default table name is omitted;
public class User {

    @Id // This is a primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)// Add the primary key
    private Integer id;

    @Column(name = "last_name",length = 50) // This is a column corresponding to the table
    private String lastName;
    @Column // Omitting the default column name is the attribute name
    private String email;
Copy the code

After creating the entity class and configuring the mapping, we write a Dao interface to manipulate the entity class’s corresponding data table (Repository).

// Inherit from JpaRepository to perform operations on the database
public interface UserRepository extends JpaRepository<User.Integer> {}Copy the code

Note that our JPA uses Hibernate by default, so we can do the following basic configuration in the configuration file

spring:  
 jpa:
    hibernate:
Update or create table structure
      ddl-auto: update
The console displays SQL
    show-sql: true
Copy the code

The next article

Here we roughly introduced SpringBoot data access methods, take you to understand some basic operations, more specific also need to learn about the relevant data access methods, the next blog post we will explain the startup principle of SpringBoot.