Spring MVC self study log 07 (Mybatic integration)

Posted by jamal dakak on Thu, 13 Feb 2020 16:50:30 +0100

Integration steps

Import related jar package

<!--junit-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<!--mybatis-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<!--mysql-connector-java-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>
<!--spring Relevant-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.1.10.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.10.RELEASE</version>
</dependency>
<!--aspectJ AOP Weaving device-->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>
<!--mybatis-spring Integration package [key points]-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>
    <!--Servlet - JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
        <!--Database driven-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- Database connection pool -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>

Configure Maven static resource filtering problem!

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

Database environment

MySQL8 or above
Maven
Building tables

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
  `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'book id',
  `bookName` VARCHAR(100) NOT NULL COMMENT 'Title',
  `bookCounts` INT(11) NOT NULL COMMENT 'Number',
  `detail` VARCHAR(200) NOT NULL COMMENT 'describe',
  KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES 
(1,'Java',1,'From getting started to giving up'),
(2,'MySQL',10,'From deleting library to running'),
(3,'Linux',5,'From entrance to prison');

Configure mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

Configure applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

Compiled by Mybatis layer

Database configuration file database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456

Write the core configuration file for MyBatis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/kuang/dao/BookMapper.xml"/>
    </mappers>

</configuration>

Write the entity class com.kuang.pojo.Books corresponding to the database (use the lombok plug-in!)

package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
    
}

Write Mapper interface of Dao layer!

package com.kuang.dao;

import com.kuang.pojo.Books;
import java.util.List;

public interface BookMapper {

    //Add a Book
    int addBook(Books book);

    //Delete a Book by id
    int deleteBookById(int id);

    //Update Book
    int updateBook(Books books);

    //According to the id query, a Book is returned
    Books queryBookById(int id);

    //Query all books and return list collection
    List<Books> queryAllBook();

}

Write the Mapper.xml file corresponding to the interface. The package of MyBatis needs to be imported;

<?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.kuang.dao.BookMapper">

    <!--Add one more Book-->
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books(bookName,bookCounts,detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    </insert>

    <!--according to id Delete one Book-->
    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID=#{bookID}
    </delete>

    <!--To update Book-->
    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
        where bookID = #{bookID}
    </update>

    <!--according to id query,Return to one Book-->
    <select id="queryBookById" resultType="Books">
        select * from ssmbuild.books
        where bookID = #{bookID}
    </select>

    <!--Query all Book-->
    <select id="queryAllBook" resultType="Books">
        SELECT * from ssmbuild.books
    </select>

</mapper>

Write the interface and implementation class of Service layer
Interface:

package com.kuang.service;

import com.kuang.pojo.Books;

import java.util.List;

//BookService: it needs to be implemented below, calling dao layer
public interface BookService {
    //Add a Book
    int addBook(Books book);
    //Delete a Book by id
    int deleteBookById(int id);
    //Update Book
    int updateBook(Books books);
    //According to the id query, a Book is returned
    Books queryBookById(int id);
    //Query all books and return list collection
    List<Books> queryAllBook();
}

Implementation class:

package com.kuang.service;

import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import java.util.List;

public class BookServiceImpl implements BookService {

    //Call the operation of dao layer and set a set interface to facilitate Spring management
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    
    public int addBook(Books book) {
        return bookMapper.addBook(book);
    }
    
    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }
    
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }
    
    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }
    
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

Spring level

Configure Spring to integrate MyBatis. Here, the data source uses c3p0 connection pool;
Let's write the related configuration file of Spring integrating Mybatis; spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Configuration integration mybatis -->
    <!-- 1.Associated database file -->
    <context:property-placeholder location="classpath:database.properties"/>
    <!-- 2.Database connection pool -->
    <!--Database connection pool
dbcp  Semi automatic operation cannot be connected automatically
c3p0  Automatic operation (automatically load the configuration file and set it in the object)
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<!-- Configure connection pool properties -->
	<property name="driverClass" value="${jdbc.driver}"/>
	<property name="jdbcUrl" value="${jdbc.url}"/>
	<property name="user" value="${jdbc.username}"/>
	<property name="password" value="${jdbc.password}"/>
	
	<!-- c3p0 Private properties of connection pool -->
	<property name="maxPoolSize" value="30"/>
	<property name="minPoolSize" value="10"/>
	<!-- Do not automatically close the connection commit -->
	<property name="autoCommitOnClose" value="false"/>
	<!-- Get connection timeout -->
	<property name="checkoutTimeout" value="10000"/>
	<!-- Number of retries when get connection failed -->
	<property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 3.To configure SqlSessionFactory object -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- Inject database connection pool -->
	<property name="dataSource" ref="dataSource"/>
	<!-- To configure MyBaties Global profile:mybatis-config.xml -->
	<property name="configLocation" value="classpath:mybatis-                         0.xml"/>
    </bean>

    <!-- 4.Configuration scan Dao Interface package, dynamic implementation Dao Interface injection to spring Container -->
    <!--Interpretation: https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- injection sqlSessionFactory -->
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
	<!-- Give the need to scan Dao Interface package -->
	<property name="basePackage" value="com.kuang.dao"/>
    </bean>

</beans>

Spring integrates service layer

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- scanning service Dependent bean -->
    <context:component-scan base-package="com.kuang.service" />

    <!--BookServiceImpl Injection into IOC Container-->
    <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- Inject database connection pool -->
<property name="dataSource" ref="dataSource" />
    </bean>

</beans>

Spring layer is done! Once again, spring is a hodgepodge, a container! Right!

SpringMVC level

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--encodingFilter-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!--Session Expiration date-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
    
</web-app>

spring-mvc.xm

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- To configure SpringMVC -->
    <!-- 1.open SpringMVC Annotation driven -->
    <mvc:annotation-driven />
    <!-- 2.Static resource default servlet To configure-->
    <mvc:default-servlet-handler/>

    <!-- 3.To configure jsp display ViewResolver view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 4.scanning web Dependent bean -->
    <context:component-scan base-package="com.kuang.controller" />

</beans>

Spring configuration integration file, applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
    
</beans>

Profile, end temporarily! Controller and view layer writing

Published 28 original articles, won praise 0, visited 383
Private letter follow

Topics: Spring Mybatis xml Database