About SpringBoot integration database

Hikari+jdbcTemplate+mysql

pom.xml

<!--        Connection pool, jdbc,Transaction related-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
<!--        mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>

yaml

spring:
#  Connection source configuration
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 333
    driver-class-name: com.mysql.jdbc.Driver
#    template configuration
  jdbc:
    template:
      query-timeout: 3

Druid+jdbcTemplate+mysql

custom

pom.xml

<!--        Connection pool, jdbc,Transaction related-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
<!--        mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--        druid data source-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>

yaml

spring:
#  Connection source configuration
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 333
    driver-class-name: com.mysql.jdbc.Driver
#    template configuration
  jdbc:
    template:
      query-timeout: 3

configuration

@Configuration
public class DataSourceConfiguration {
    /**
     * Add druid data source to container
     * @return
     */
    @Bean
    @ConfigurationProperties(value = "spring.datasource")
    public DataSource dataSource(){
        return new DruidDataSource();
    }

    /**
     * Configure the Servlet of the monitoring page
     * @return
     */
     @Bean
    public ServletRegistrationBean statViewServlet(){
        StatViewServlet statViewServlet = new StatViewServlet();
        return new ServletRegistrationBean<StatViewServlet>(statViewServlet,"/druid/*");
    }
}

tips:
Adding a Servlet in SpringBoot is very simple. Write a configuration class and add a ServletRegistrationBean component. The creation of the component requires two parameters: the Servlet object and the path to be mapped. Adding a Filter is the same, but the mapping path should be configured with the setter method

official

pom.xml

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>

yaml

spring:
#  Connection source configuration
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 333
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      aop-patterns: com.atguigu.admin.*  #Monitoring springbeans
      filters: stat,wall     # Bottom open function, stat (sql monitoring), wall (firewall)

      stat-view-servlet:   # Configure monitoring page function
        enabled: true
        login-username: admin
        login-password: admin
        resetEnable: false

      web-stat-filter:  # Monitoring web
        enabled: true
        urlPattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'


      filter:
        stat:    # Detailed configuration of stat in the above filters
          slow-sql-millis: 1000
          logSlowSql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false
#    template configuration
  jdbc:
    template:
      query-timeout: 3

Druid+Mybatis+mysql

pom.xml

Initialization Wizard

<!--        Connection pool, jdbc,Transaction related-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
<!--        mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
<!--        druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

yaml

spring:
#  Connection source configuration
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 333
    driver-class-name: com.mysql.jdbc.Driver

    druid:
      aop-patterns: com.atguigu.admin.*  #Monitoring springbeans
      filters: stat,wall     # Bottom open function, stat (sql monitoring), wall (firewall)

      stat-view-servlet:   # Configure monitoring page function
        enabled: true
        login-username: admin
        login-password: admin
        resetEnable: false

      web-stat-filter:  # Monitoring web
        enabled: true
        urlPattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'


      filter:
        stat:    # Detailed configuration of stat in the above filters
          slow-sql-millis: 1000
          logSlowSql: true
          enabled: true
        wall: #firewall
          enabled: true
          config:
            drop-table-allow: false
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml  #The location of the sql mapping file is used only when writing sql through configuration
  configuration: #In the future, we will configure the configuration in mybatis here
    map-underscore-to-camel-case: true

mapper.xml(sql configuration file, the same as in mybatis)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bianys.demo.mapper.ClientMapper">
    <select id="getAll" resultType="com.bianys.demo.domain.Client">
        select * from  client
    </select>
</mapper>

mapper

The Mapper class needs to be annotated with @ Mapper. You can also add MapperScan("package path") in the main configuration class. The classes under the specified package path are mappers

package com.bianys.demo.mapper;

import com.bianys.demo.domain.Client;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper//This is the mapper annotation
public interface ClientMapper {
    public List<Client> getAll();
}

Annotation method

pom.xml is the same as before. yaml can not write mapper XML, let alone mapper, is the same as in mybatis

package com.bianys.demo.mapper;


        import com.bianys.demo.domain.Client;
        import org.apache.ibatis.annotations.Insert;
        import org.apache.ibatis.annotations.Mapper;
        import org.apache.ibatis.annotations.Options;
        import org.apache.ibatis.annotations.Select;
        import org.springframework.stereotype.Component;

        import java.util.List;

@Mapper
public interface ClientMapper {

    public List<Client> getAll();

    @Select(value = "select id from client")
    public List<Integer> getAllId();

    @Insert("insert into client(`range`) values(#{range})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    public void insertClient(Client client);
}

summary

  • Introducing mybatis starter
  • Configure application In yaml, specify the mapper location
  • Write Mapper interface and annotate @ Mapper annotation
  • Simple method direct annotation method
  • Write mapper with complex method XML binding mapping
  • @MapperScan("com.atguigu.admin.mapper") is simplified, and other interfaces do not need to be annotated with @ mapper annotation

Druid+MybatisPlus+mysql

For details, please refer to Official documents

pom.xml

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!--        druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>
<!--        mybatis-plus-->        
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.1</version>
        </dependency>

yaml

Same as mybatis

mapper,service,serviceImpl

After these three classes are configured, the xxserviceimpl class has a large number of methods to operate the database. Of course, we can also use mybatis according to mybatis. You can still use mybatis as you like with mybatis plus

  • mapper
package com.bianys.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bianys.demo.bean.User;
//Do not configure @ Mapper annotation
public interface UserMapper extends BaseMapper<User> {
}
  • service
public interface UserService extends IService<User> {
}
  • serviceImpl
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

Auto configuration

  • The MybatisPlusAutoConfiguration configuration class is bound to the MybatisPlusProperties configuration item. Mybatis plus: xxx is the customization of mybatis plus
  • SqlSessionFactory is automatically configured. The bottom layer is the default data source in the container
  • Maperlocations is automatically configured. There are default values. classpath*:/mapper/**/*.xml; All XML in any path under all mapper folders under the classpath of any package are sql mapping files. It is recommended to put the sql mapping file under mapper in the future
  • SqlSessionTemplate is also automatically configured in the container
  • @The interface marked by mapper will also be automatically scanned; It is recommended to directly scan @ MapperScan("com.atguigu.admin.mapper") in batches

@TableName, tablefile, @ TableId and other annotations

  • @TableName: put it on the domain class and specify the name of the table corresponding to the class in the database
@TableName("t_user")
public class User {
  • @Tablefile: put it on the attribute. When its select value is false, the attribute will not participate in the operation of the database
    @TableField(select = false)
    private String username;
  • @TableId(): placed on the attribute. Its value is the field name of the primary key in the table
@TableId("id")
    private Integer id;

Configure paging

Add a configuration class to take effect

    // the latest version
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.H2);
        //Set whether to roll back the current page
        paginationInnerInterceptor.setOverflow(true);
        //Set maximum requested pages
        paginationInnerInterceptor.setMaxLimit(3L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

redis+Lettuce

pom.xml

<!--        redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

yaml

  redis:
  # Database address
    #    host: r-bp1bdn6tbx3521mnw2pd.redis.rds.aliyuncs.com
  # Database password
    #    password: 1z2x3c4v5b-
    url: redis://:bianys:1z2x3c4v5b-@r-bp1bdn6tbx3521mnw2pd.redis.rds.aliyuncs.com:6379

use

Import the StringRedisTemplate class through Spring to operate the redis database through the StringRedisTemplate object

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("hello", "helloWorld");
        String hello = operations.get("hello");
        System.out.println(hello);
    }
}

redis+jedis

pom.xml

<!--        redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--        jedis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${jedis.version}</version>
        </dependency>

yaml

  redis:
  # Database address
    #    host: r-bp1bdn6tbx3521mnw2pd.redis.rds.aliyuncs.com
  # Database password
    #    password: 1z2x3c4v5b-
    url: redis://:bianys:1z2x3c4v5b-@r-bp1bdn6tbx3521mnw2pd.redis.rds.aliyuncs.com:6379
    clientType: jedis
    jedis:
      pool:
        max-active: 10

use

Like lattice, lattice is the default package that operates redis database

Keywords: Java Database MySQL Mybatis Spring

Added by jockey_jockey on Sat, 22 Jan 2022 09:02:35 +0200