springboot integrates mybatis, mybatisplus, jpa, druid data source, jsp template engine

1springboot integrates jsp template engine

To create a springboot project, select several common dependencies, such as lombook and spring web dependencies, etc.

Because jsp is not integrated in the srpingboot project, import the following jsp dependencies into the pom file in the springboot project:

<dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

Then click project Structure

Click modules, add the web module above, then the web folder will appear in the project directory, create WEB-INF/view in the web file, and then the jsp file can be placed under this file.

Configure the default access path of the jsp template in the yml file:

spring:
  mvc:
    view:
      prefix: /WEB-INF/view/
      suffix: .jsp

Because: this path is written in the source code.

2springboot integrates jpa

2.1 Select the appropriate database driver when creating the springboot project (this is the mysql driver I chose), and select the jpa dependency

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

2.2 Create beans

package com.it.springbootrabbitmq.bean;


import lombok.*;

import javax.persistence.*;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity //Tell JPA this is an entity class
@Table(name="role")
public class role {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    String role_id;
    @Column(name = "role_name",length = 25)
    String role_name;
    String role_description;
    String role_state;
}

Here I created a role, corresponding to the role table in the database. Note: Must use

@Entity //This annotation tells JPA that this is an entity class

@table (name=”role”) tells jpa which table in the database this entity class corresponds to

@id and @GeneratedValue(strategy = GenerationType.IDENTITY) tell the primary key of the jpa table and the data type of the primary key

@colum is the field corresponding to the database. Of course, the field name does not need to be written.

2.3 Create dao interface

package com.it.springbootrabbitmq.ee;

import com.it.springbootrabbitmq.bean.role;
import org.springframework.data.jpa.repository.JpaRepository;

public interface roleRepository extends JpaRepository<role,String> {
}

The interface inherits JpaRepository, followed by the bean name and primary key data type. This interface will be called later, which defines a series of operations for a single table. Of course, you can also define some of your own methods in this interface.

No explanation here.

3springboot integrates druid data source

3.1 Import druid data source dependencies

 <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

3.2yml file configuration related parameters (including database connection parameters and druid own parameters)

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/xianmu?useSSL=false
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource #Switch data source
    filters: stat,wall,log4j2



    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    logging:
      level:
        com.alibaba.druid.filter.logging.Slf4jLogFilter: info

Type defines the type of data source. Above type is the MySQL database connection information, and below type is the relevant information about the druid data source, such as the size of the connection.

logging:
  level:
    com.alibaba.druid.filter.logging.Slf4jLogFilter: info

This is the sql statement printed and executed when searching for data. 

3.3 Configure druid configuration class

package org.example.springbootmybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class druidconfig {


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

    //Cooperate with druid monitoring

    /**
     * Monitoring address: http://localhost:8080/druid/login.html
     * Monitoring request: http://localhost:8080/query
     * @return
     */
    //1. Configure a servlet for management background
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean= new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        Map<String,String> map=new HashMap<>();
        map.put("loginUsername","admin");
        map.put("loginPassword","123456");
        map.put("allow","localhost");//Allow local access
        map.put("deny","192.168.122.133");//Access denied
        bean.setInitParameters(map);
        return bean;
    }
    //2. Configure a monitoring filter
    @Bean
    public FilterRegistrationBean webStatFilter(){

        FilterRegistrationBean bean= new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,String> map=new HashMap<>();
        map.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(map);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return bean;
    }


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

The first annotation is the key to making Druid use that data. Connect to the database.

The following two configurations mainly provide a web page with some database-related information.

4springboot integrates mybatis

4.1mybatis introduction

MyBatis (also known as iBatis) is an open source persistence layer framework used to separate database operations from the business logic of an application. It provides a simple and flexible way to map database tables and SQL query results to Java objects.

The main goal of MyBatis is to achieve access to the database through the use of simple XML or annotation configuration, while providing powerful capabilities for building dynamic SQL statements. It supports a variety of databases, including relational databases (such as MySQL, Oracle, PostgreSQL, etc.) and non-relational databases (such as MongoDB).

Using MyBatis, you can define database operations, including inserts, updates, deletes, and queries, by writing SQL mapping files or annotations. MyBatis maps these operations with Java objects, making data reading and writing operations more concise and easier to maintain.

The core principle of MyBatis is to bind SQL statements to Java methods based on configuration information in SQL mapping files or annotations, and perform corresponding database operations through JDBC. It provides a wealth of functions, such as parameter mapping, result set mapping, dynamic SQL, transaction management, etc., to meet the needs of different scenarios.

To sum up, MyBatis is a lightweight, easy-to-learn and use persistence layer framework that provides a flexible and efficient way to access and operate the database by decoupling database operations from applications.

4.2 Import dependencies into pom files

Of course, you can also select the spring –mybatis option when creating a springboot project, so that it can be automatically imported. If not, you need to import it separately:

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter-test</artifactId>
            <version>2.3.1</version>
            <scope>test</scope>
        </dependency>

4.3 If there is a data source, configure mybatisconfig

package org.example.springbootmybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class mybaticeconfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }
}

If not, no need.

4.4 Create mapper interface and xml file (annotations can be used instead of xml files)

package org.example.springbootmybatis.mapper;


import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.example.springbootmybatis.bean.Student;

import java.util.List;

public interface studentMapepr {

 @Select("select * from role")
    public List<Student> fandall();
}

Of course, you need to enable the mapper agent: two methods:

1. Use the @mapper annotation on the mapper interface to indicate that this is a mapper proxy interface

2. Use it on the startup class

@MapperScan(basePackages = "org.example.springbootmybatis.mapper")

Scan the mapper interface to get the package.

Just write the corresponding method in the interface. You can use annotations or write xml files, but they must be placed in the mapper in the root directory. Of course, you can also change the default location of the xml file in the yml file.

<?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="org.example.springbootmybatis.mapper.studentMapepr">
    <select id="fandall" resultType="org.example.springbootmybatis.bean.Student">
        select * from role
    </select>
</mapper>

Finally, just call this interface.

5.springboot integrates mybatisplus

5.1 Import dependencies of mybatisplus

<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.3.2</version>
        </dependency>

5.2 If you want to do paging operation, configure the mybatisplusconfig configuration class

package com.it.springbootmybaticeplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class mybaticeplusconfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}

5.3 Add database connection information in the yml file

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/xuexi?useSSL=false &characterEncoding=utf8
    username: root
    password: 123456
      #sql:
      #init:
      #schema-locations: classpath:sql/data.sql # DDL?resources/sql/schema.sql
      #data-locations: classpath:sql/data.sql # sql?resources/sql/data.sql
    #mode: always


    #type: com.alibaba.druid.pool.DruidDataSource #Switch data source
    #filters: stat,wall,log4j2



    #initialSize: 5
    #minIdle: 5
    #maxActive: 20
    #maxWait: 60000
    #timeBetweenEvictionRunsMillis: 60000
    #minEvictableIdleTimeMillis: 300000
    #validationQuery: SELECT 1 FROM DUAL
    #testWhileIdle: true
    #testOnBorrow: false
    #testOnReturn: false
    #poolPreparedStatements: true

    #logging:
      #level:
         # com.alibaba.druid.filter.logging.Slf4jLogFilter: info


#security:
#user:
# name: zhou
# password: 123456


mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: false
  # If placed in the src/main/java directory classpath:/com/*/*/mapper/*Mapper.xml
  # If placed in the resource directory classpath:/mapper/**.xml
  mapper-locations: classpath:/mapper/**.xml
configuration:
  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  map-underscore-to-camel-case: false

This is not to modify our table fields. Turn off camel case naming, etc.

mapper-locations: classpath:/mapper/**.xml

This is the location where the mapper.xml file is placed. I won’t introduce them one by one before.

5.4mapper interface and xml file, etc.

This content is roughly the same as mybatis. The only difference is that when creating an interface, you need to inherit a class.

BaseMapper<role> receives the table name, which is the bean.
package com.it.springbootmybaticeplus.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.springbootmybaticeplus.bean.role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface roleMapper extends BaseMapper<role> {

    @Select("select * from role ${ew.customSqlSegment}")
    public Page<role> selectByPrimaryKey(Page<role> page,
                                         @Param(Constants.WRAPPER) QueryWrapper<role> queryWrapper);




   public Page<role> selectPage(@Param("page") Page<role> page,
                             @Param("role_id") String role_id);


}

5.5 related explanations

Use @Param annotation

When writing SQL statements in the following way:

@Select(“select column from table where userid = #{userid} “)

public int selectColumn(int userid);

When you use the @Param annotation to declare parameters, you can use #{} or ${}.

@Select(“select column from table where userid = ${userid} “)

public int selectColumn(@Param(“userid”) int userid);

When you do not use the @Param annotation to declare parameters, you must use the #{} method. If you use ${}, an error will be reported.

@Select(“select column from table where userid = ${userid} “)

public int selectColumn(@Param(“userid”) int userid);

2) Do not use @Param annotation

When the @Param annotation is not used, there can only be one parameter, and it is a Javabean. JavaBean properties can be referenced in SQL statements, and only JavaBean properties can be referenced.

//Here id is the attribute of user

@Select(“SELECT * from Table where id = ${id}”)

Enchashment selectUserById(User user);

5.6Wrapper passing parameters + annotation SQL

5.6.1?Create custom methods and sql in the interface

public interface StudentMapper extends BaseMapper<Student> {
    @Select("select * from student ${ew.customSqlSegment}")
    public Page<Student> selectByPrimaryKey(Page<Student> page,
@Param(Constants.WRAPPER) QueryWrapper<Student> queryWrapper);

}

Create test class:

@RequestMapping("/findStudentByWrapper")
@ResponseBody
public Page<Student> findStudentByWrapper(){
    //Create Wrapper object
    QueryWrapper<Student> wrapper = new QueryWrapper<>();
    //Set query conditions
    wrapper.eq("stu_id", "1001")
            .like("stu_name", "Xiaochun");
    //Set sorting conditions - optional conditions
    //wrapper.orderByAsc("stu_id");
    //Set paging parameters-optional conditions
    Page<Student> resultPage = new Page<>(1, 10);
    Page<Student> list=studentMapper.selectByPrimaryKey(resultPage,wrapper);
    return list;
}

There is another way (not commonly used):

@RequestMapping("/findStudentByWrapper")
@ResponseBody
public IPage<Student> findStudentByWrapper(){
    /*//Create Wrapper object
    QueryWrapper<Student> wrapper = new QueryWrapper<>();
    //Set query conditions
    wrapper.eq("stu_id", "1001")
            .like("stu_name", "Xiaochun");
    //Set sorting conditions - optional conditions
    //wrapper.orderByAsc("stu_id");
    //Set paging parameters-optional conditions
    Page<Student> resultPage = new Page<>(1, 10);
    Page<Student> list=studentMapper.selectByPrimaryKey(resultPage,wrapper);*/

    //Paging query method 2
    IPage<Student> page = new Page<>(1, 10); // Paging query
    LambdaQueryWrapper<Student> qw = new LambdaQueryWrapper<Student>()
            .like(Student::getStu_name, "Xiaochun") // Name
            .eq(Student::getStu_id, "1001"); // id
    //selectPage is the built-in method of BaseMapper
    IPage<Student> userPage = studentMapper.selectPage(page, qw);
    return userPage;

Well, that’s it for the last few days. Tomorrow we will continue to introduce springboot’s integration of security and rambbittmq. I wish you all a happy life! ! ! !