ssm integration notes

Keywords: Java JavaEE Spring

5. Spring MVC integrates Mybatis

5.1 start

1. Create database

2. Create a normal maven project and add a web service

3. Import package (pom.xml)

4. Connect to the database

5. Create directory structure

6. Configure all xml files

7.pojo entity class

8. Database operation of Dao layer (two files, file name: bookMapper (Interface) bookMapper.xml)

9.Service layer (two files, file name: bookService (Interface) bookServiceImpl.xml): the service layer calls the Dao layer

10.Controller layer (bookController (class) controls interaction with the front end)

11. Connect Tomcat, check the environment, and add the lib directory,

12. Test

Normal ssm framework integration sequence after proficiency:

Mybatis{

1. Entity class

2. The Mapper interface of Dao layer mainly defines methods such as addition, deletion, query and modification

3. The Dao layer Mapper.xml mainly implements addition, deletion, query and modification, and SQL statements

4. Configuration file: applicationContext.xml (not used for the time being. It is used to import the configuration file of dao layer and service layer mvc during later integration)

database.properties (database configuration file)

​ mybatis-config.xml

5.service layer, service interface and ServiceImpl class, business layer calls dao layer

}

Spring integration Dao layer: spring-dao.xml

Spring integration service layer: spring-service.xml

spring mvc{

1. Add Web support

2. Configure Web.xml

3. Configure spring-mvc.xml

}

5.2 pom.xml

Including junit,mysql,c3p0,mybatis,

​ mybatis-spring,servlet-api,

​ jsp-api,jstl,spring-jdbc

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Lei_xiaoFan</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>

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

    </build>

</project>

5.3 directory structure

[external chain picture transfer fails, the source station may have anti-theft chain mechanism, so it is recommended to save the picture and upload it directly (img-yzesigag-1636269743677) (C: \ users \ Lei \ appdata \ roaming \ typora \ typera user images \ image-20210904113831008. PNG)] [external chain picture transfer fails, the source station may have anti-theft chain mechanism, so it is recommended to save the picture and upload it directly (img-SDHBKCHL-1636269743681)(C:\Users\lei\AppData\Roaming\Typora\typora-user-images\image-20210904113905959.png)]

5.4 configuration files

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="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
</beans>

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>

    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.kuang.dao.BookMapper"/>
    </mappers>

</configuration>

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

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
       http://www.springframework.org/schema/context/spring-context.xsd">
    
<!--Associated database profile-->
    <context:property-placeholder location="classpath:database.properties"/>

<!--Connection pool: the connection pool type is c3p0-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
<!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--binding Mybatis configuration file-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
<!--to configure dao Interface scanning package, which can be implemented Dao Interface dynamic injection spring container-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

        <property name="basePackage" value="com.kuang.dao"/>
    </bean>
</beans>

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:contex="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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd">
<!--Annotation driven-->
    <mvc:annotation-driven/>
<!--Static resource filtering-->
    <mvc:default-servlet-handler/>
<!--Scan package-->
    <contex:component-scan base-package="com.kuang.controller"/>
<!--view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

spring-serivce.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
       http://www.springframework.org/schema/context/spring-context.xsd">
<!--scanning service package-->
    <context:component-scan base-package="com.kuang.service"/>
<!--Inject all business into spring-->
    <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
<!--Declarative transaction configuration-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--aop Transaction support-->
    
</beans>

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: Core distributor-->
    <servlet>
        <servlet-name>springmvc</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>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--Filter: random code filtering-->
    <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 time-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

5.5 entity class

pojo (class)

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;

}

5.6Dao layer file

bookMapper (Interface)

package com.kuang.dao;

import com.kuang.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {

    int addBook(Books books);

    int deleteBookById(@Param("bookId") int id);

    int updateBook(Books books);

    Books queryBookById(@Param("bookId") int id);

    List<Books> queryAllBook();

    Books queryBookByName(@Param("bookName") String bookName);
}

bookMapper.xml

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

<mapper namespace="com.kuang.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName,bookCounts,detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookId}
    </delete>

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

    <select id="queryBookById" resultType="Books">
        select * from ssmbuild.books
        where bookID=#{bookId}
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from ssmbuild.books
        where bookName=#{bookName}
    </select>
</mapper>

5.7 service layer

BookService (Interface)

package com.kuang.service;

import com.kuang.pojo.Books;

import java.util.List;

public interface BookService {
        int addBook(Books books);

        int deleteBookById(int id);

        int updateBook(Books books);

        Books queryBookById(int id);

        List<Books> queryAllBook();

        Books queryBookByName(String bookName);
}

The BookServiceImol class implements the BookService interface

package com.kuang.service;

import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public class BookServiceImpl implements BookService{

    private BookMapper bookMapper;
    //The business layer calls the dao layer, and some operations can be added
    public  void  setBookMapper(BookMapper bookMapper){
        this.bookMapper = bookMapper;
    }

    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }

    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();
    }

    public Books queryBookByName(String bookName){
        return bookMapper.queryBookByName(bookName);
    }
}

5.8 controller layer

package com.kuang.controller;

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
//The controller calls the service layer
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "AllBook";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "AddBook";
    }

    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("addBook->"+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/delBook/{bookId}")
    public String delBook(@PathVariable("bookId") int id){
        System.out.println("delBook->"+id);
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
        System.out.println("toUpdateBook->"+id);
        Books books = bookService.queryBookById(id);
        model.addAttribute("Qbook",books);
        System.out.println(books);
        return "UpdateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        System.out.println("updateBook->"+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/queryBook")
    public  String queryBook(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);

        List<Books> list = new ArrayList<Books>();
        if(books!=null) list.add(books);
        model.addAttribute("list",list);
        return "AllBook";
    }
}

5.9 testing

The main purpose is to test whether the tomact connection is successful and whether the program can run normally

In browser http://localhost:8080/hello test

package com.kuang.controller;

import com.kuang.pojo.Books;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller

public class LController {
    @RequestMapping("/hello")
    @ResponseBody
    public String Hello(){
        return "hello";
    }

}

5.10 possible errors

1. There is a jar package problem in the lib directory

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-gjmzhewz-16362697433684) (C: \ users \ Lei \ appdata \ roaming \ typora \ typora user images \ image-20210904113436483. PNG)]

2. jsp problem

The. jsp file is placed under / WEB-INF/jsp

However, sometimes there is an error that the access is less than 404

The possible reason is that the out folder is not updated. Sometimes there will be no jsp folder here. Please go to Baidu,

One solution: [the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-bt9cc773-1636269743687) (C: \ users \ Lei \ appdata \ roaming \ typora \ typora user images \ image-20210904113540549. PNG)]

If it can't be solved, you can directly copy the jsp folder below here, which can also be run.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1yol7pkg-1636269743689) (C: \ users \ Lei \ appdata \ roaming \ typora \ user images \ image-20210904113644386. PNG)]

3. SQL problems

If you encounter an error, you can use Test to Test whether it is a SQL statement.

example:

When I delete a book, an error occurs, saying that the book ID cannot be found

However, all previous pages can be accessed, so I conducted a test

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookServiceImpl = (BookService) context.getBean("BookServiceImpl");
        bookServiceImpl.deleteBookById(3);
    }
}

If there is still an error, you can determine the problem in the SQL statement

(img-1YoL7PKG-1636269743689)]

3. SQL problems

If you encounter an error, you can use Test to Test whether it is a SQL statement.

example:

When I delete a book, an error occurs, saying that the book ID cannot be found

However, all previous pages can be accessed, so I conducted a test

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookServiceImpl = (BookService) context.getBean("BookServiceImpl");
        bookServiceImpl.deleteBookById(3);
    }
}

If there is still an error, you can determine the problem in the SQL statement

After re running, it is found that the deletion is successful and the problem is solved.

Posted by zulfer on Mon, 08 Nov 2021 02:06:30 -0800