Remove the ready-to-use spring mvc and integrate mybatis (crud + paging plug-in) to operate mysql

1. Auto-encapsulation of 32-bit uuid for insertion data by annotations

2. Automatically encapsulating insertion date by annotation

3. Annotation realizes automatic update date of update data

4. Paging query auto-encapsulation returns the total number of qualified queries

5. Encapsulating data validation for arbitrary requests

6. Encapsulating Return Data Format and Unified Exception Handling

I. web.xml Configuration

We all know that the first thing to start a java ee project is to read web.xml, spring mvc's web.xml, which I explained in detail in the last article. If you don't understand it, you can look back. I will put the source code of the project on github, you can also go there to see it. I will not introduce it here.

web.xml configuration

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:/context.xml</param-value>
</context-param>

<!-- Listener: Start the server when it starts spring -->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- spring Core Controller -->
<servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
<init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:external-servlet.xml</param-value>
</init-param>
</servlet>

<servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- Coding filter -->
<filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
</init-param>
<init-param>
  <param-name>forceEncoding</param-name>
  <param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

2. spring (context.xml) context configuration

This configuration file can be said to be the second one to be read by the server container. It configures the base package path scanned at spring startup, the import of the external configuration property files, the configuration of the database to be connected, the integration of mybatis and spring, the mybatis date plug-in and paging plug-in we mentioned at the beginning, and the reality of mybatis scanning. The location of the package and its mapper file is now available.

context.xml configuration

<!-- spring Scanning Base Pack Path -->
<context:component-scan base-package="com.qbian" />

<!-- jdbc properties -->
<bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="classpath:jdbc.properties" />

<!-- define the datasource (Here we use c3p0 Looking at the connection pool for data, the performance is not very good. It can call other better connection pools.[jdbc pool etc.])-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
      destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />

</bean>

<!-- define the SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="typeAliasesPackage" value="com.qbian.**.dto" />
    <property name="plugins">
        <list>
            <!-- Configure your own date plug-in -->
            <bean class="com.qbian.common.plugin.DatePlugin" />
            <!-- jPaginate -->
            <bean class="com.qbian.common.plugin.PagePlugin"  />
        </list>
    </property>
</bean>

<!-- scan for mappers and let them be autowired -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.qbian.**.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

<!-- Read multiple configuration files into the container and hand them in Spring Administration -->
<bean id="configProperties" class="com.qbian.common.plugin.PropertiesConfigurer">
    <property name="locations">
        <list>
            <!--<value>classpath:redis.properties</value>-->
        </list>
    </property>
</bean>

3. spring Controller Configuration

The location of the controller and the type and coding of requests it supports are configured here.

external-servlet.xml configuration

<!-- Controller Scanning -->
<context:component-scan base-package="com.qbian.common.controller" />

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
            <property name="writeAcceptCharset" value="false" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Configuration information is the above three, let's take a look at the specific code.

IV. Code Explanation

1. The explanation of Java code is arranged in the order shown by the editor instead of sorting. (The following are all in the java.com.qbian package)

 common |
    annotation |
        @interface Now : insert|Date annotation for updating data.
        @interface UUID :Inserted data uuid Annotations.
    controller |
        ExternalController.class :Core controller, intercepting all requests, exception handling, cross-domain settings and other functions.
    dao |
        interface StudentDao :Using examples, crud Common methods.
    dto |
        PageInfoDto.class :Foundation of Paging Use dto Object.
        ResponseDto.class :The basic model of response data.
    entity |
        Student.class :Use examples to customize the use of annotations.
    enums |
        enum MessageEnum :Unified return status code and description information.
    exception |
        ExternalServiceException.class :Customize the exception, and business-related throws the exception object.
    factory |
        BeanFactoryUtil.class :according to bean name Obtain spring Managerial bean Example.
    hadle |
        ExceptionHandle.class :spring Unified exception capture processing.
    plugin |
        DatePlugin.class :custom mybatis Date plug-in.
        PagePlugin.class :custom mybatis Paging plug-in.
        PropertiesConfigurer.class :Read the external configuration properties file to spring Unified management in containers.
    service |
        interface IbaseServie :Basic service Interface.
        BaseService.class :Basic service Abstract class.
        TokenService.class :authentication token Service class.
    util |
        CheckUtil.class :Request information validation related tool classes.
        DateUtil.class :Date related tool class.
        ResponseUtil.class :Response information tool class.
        SecondsFormatSerializer.class :java.util.Date Type-to-timestamp tool class.
        TimestampSecondsFormatSerializer.class :java.sql.Timestamp Type-to-timestamp tool class.
        StringUtil.class :String-related tool classes.

other |
    dao |
        interface StudentExtDao :Use examples, business-related crud Operation.
    dto |
        QueryStudentSexPageDto.class :Paging Query Returns Objects Based on Students'Gender dto. 
        StudentPageDto.class :Search the encapsulated objects according to students'gender.
    service |
        AddStudentService.class :Insert student data interface.
        DeleteStudentService.class :Delete student data interface.
        FindStudentService.class :Query the student data interface.
        UpdateStudentService.class :Update student data interface.
        QueryStudentBySexService.class :Paging query interface according to students'gender.

2. The mapper.xml explanation of mybatis (the following contents are in the resources/com/qbian folder)

common |
    dao |
        StudentDao.xml :Corresponding common.dao.StudentDao Interface.
other |
    dao |
        StudentExtDao.xml :Corresponding other.dao.StudentExtDao Interface.

Functional Demonstration

1. token check
Here, token I wrote dead in the code, 123456 means that the verification was successful. Let's test it with the insertion data interface and pass an incorrect token as follows:


Authorized token verification

2. Request parameter verification
Let's see what values need to be checked for inserting data interfaces.

// Check request parameters
CheckUtil.checkEmpty(params, "token", "sex", "age");
// Check token
tokenService.checkUserLogin(params.getString("token"));

Student student = JSONObject.parseObject(params.toJSONString(), Student.class);

studentDao.insert(student);

return ResponseUtil.success();

Then let's try passing the age field:


Request field validation

3. Insert data
Before inserting data, let's look at what data are in the database.


Initialize the values in the database


As can be seen from the figure above, there is no data in the database. Let's execute the next insert interface.


Test Insertion Interface


Let's look at the database again:


After calling the insert interface


The database already has data.

4. Query data
ID query based on the previous data


Invoke query interface


We also queried the data just inserted.

5. Update data
Update the queried data:


Call Update Interface


Then we query the data again.


Query again after updating


You can see that both gender and age have been updated, and the update date is up to date.

6. Paging query
Let's first look at the code:

// Check request parameters
CheckUtil.checkEmpty(params, "token", "sex", "pageNo", "pageSize");
// Check token
 tokenService.checkUserLogin(params.getString("token"));

// According to the gender paging query Student, the total number of queries is automatically encapsulated on the pageDto object.
QueryStudentSexPageDto pageDto = JSONObject.parseObject(params.toJSONString(), QueryStudentSexPageDto.class);

List<Student> students = studentExtDao.queryBySexWithPage(pageDto);

StudentPageDto studentPageDto = new StudentPageDto();
// The total number of queries is automatically encapsulated on the pageDto object
studentPageDto.setTotalSize(pageDto.getTotalSize());
studentPageDto.setStudents(students);

 return ResponseUtil.success(studentPageDto);

We want to import a little more test data before paging queries.


Pre-paging test data


It can be seen that there are currently ten test data in the database, six for boys, aged 19-24, respectively. Okay, let's start calling the paging query interface:


Calling Paging Query Interface to Return Result


Format the return data:


Paging Query Returns Result Arrangement


This is the same as what we see when we query the database directly.

7. Delete data
Finally, we deleted the data interface, and we deleted the first test data.


Call Delete Interface to Return Result


Then we'll check to see if it's really deleted.


Query after deletion


The data has been deleted.

Okay, that's what spring mvc is talking about today. It integrates mybatis crud + paging operation mysql.

Finally, the source code of the project is attached. https://github.com/Qbian61/spring-mvc-mybatis
My blog: https://qbian61.github.io/

Tags: Spring xml Mybatis Database

Posted on Sun, 16 Dec 2018 06:12:04 -0800 by smiley_kool