SSM integration Spring+SpringMVC+Mybatis

Keywords: Spring xml Mybatis MySQL

Chapter 1: building an integrated environment

1. Build an integrated environment

  1. Integration Description: there are many ways to integrate SSM. We will choose XML + annotation

  2. The idea of integration

    1. Build an integrated environment first

    2. First, set up the Spring configuration

    3. Using Spring to integrate Spring MVC framework

    4. Finally, use Spring to integrate MyBatis framework

  3. Create database and table structure

    1. Sentence
create database ssm;
use ssm;
create table account(
	id int primary key auto_increment,
	name varchar(20),
	money double
)
  1. Create maven projects (today we will use the concept of aggregation and splitting of projects, which maven will talk about)

    1. Create the parent project of SSM ﹣ parent (pom is selected for packaging method, which is required)

    2. Create the SSM web sub module (packaged by war package)

    3. Create the SSM service sub module (the packaging method is jar package)

    4. Create the SSM Dao sub module (packaged by jar package)

    5. Create the SSM domain submodule (packaged by jar package)

    6. web depends on service, service depends on dao, dao depends on domain

    7. Introducing coordinate dependency into pom.xml file of SSM parent

<properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
    <!-- spring -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.8</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- log start -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>
</dependencies>
<build>
    <finalName>ssm</finalName>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

  1. To deploy the project of SSM web, just add the project of SSM web to the tomcat server

  2. Write entity classes in the SSM domain project

import java.io.Serializable;


public class Account implements Serializable {
    private static final long serialVersionUID = 7355810572012650248L;
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }
}

  1. Write dao interface
import cn.itcast.domain.Account;

import java.util.List;


public interface AccountDao {
    public void saveAccount(Account account);

    public List<Account> findAll();
}

  1. Write service interface and implementation class
import java.util.List;
import cn.itcast.domain.Account;
public interface AccountService {
	public void saveAccount(Account account);
	public List<Account> findAll();
}




import java.util.List;
import org.springframework.stereotype.Service;
import cn.itcast.dao.AccountDao;
import cn.itcast.domain.Account;
import cn.itcast.service.AccountService;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
	private AccountDao account;
	public void saveAccount(Account account) {
	}
	public List<Account> findAll() {
		System.out.println("Business layer: query all accounts...");
		return null;
		}
}

Chapter 2: writing of Spring framework code

  1. Build and test the Spring development environment
<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- Turn on annotation scanning. What to scan is service and dao Comment of layer, to be ignored web Layer annotation because web Layer let SpringMVC Framework to manage -->
    <context:component-scan base-package="cn.itcast">
        <!-- Configure comments to ignore -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

  1. Write test method in SSM web project and test
import cn.itcast.service.AccountService;

import org.junit.Test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class ServiceTest {
    @Test
    public void run1() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "classpath:applicationContext.xml");
        AccountService as = (AccountService) ac.getBean("accountService");
        as.findAll();
    }
}

Chapter 3: Spring integrates spring MVC framework

1. Build and test the development environment of spring MVC

  1. Configuring the dispatcher servlet front-end controller in web.xml
<! -- configure the front-end controller: the server must be loaded when starting, and the springmvc.xml configuration file needs to be loaded -- >
<servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <! -- configure the initialization parameters, create the DispatcherServlet object, and load the springmvc.xml configuration file -- >
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <! -- when the server starts, let the DispatcherServlet object create -- >
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  1. Configuring the dispatcher servlet filter in web.xml to solve the Chinese confusion
<!-- Configure the filter to solve Chinese disorder -->
<filter>
	<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

  1. Create the configuration file of springmvc.xml and write the configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- scanning controller No other scanning -->
    <context:component-scan base-package="cn.itcast">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- Configure view resolver -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- JSP Directory of files -->
        <property name="prefix" value="/WEB-INF/pages/" />
        <!-- Suffix of the file -->
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- Set static resources not to filter -->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <!-- Open right SpringMVC Annotation support -->
    <mvc:annotation-driven />
</beans>
  1. Test whether the framework of spring MVC is built successfully

    1. Write index.jsp and list.jsp, hyperlink
<a href="account/findAll">Query all</a>
2. Create the AccountController class, write methods, and test
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("/account")
public class AccountController {
    /**
    * Query all data
    * @return
    */
    @RequestMapping("/findAll")
    public String findAll() {
        System.out.println("Performance layer: query all accounts...");

        return "list";
    }
}

2. Spring integrates the framework of spring MVC

  1. Objective: to successfully call the methods in the service object in the controller.

  2. When the project starts, load the configuration file of applicationContext.xml and configure it in web.xml

<! -- configure the listener of Spring. Only the applicationContext.xml configuration file under the WEB-INF directory is loaded by defau lt -- >
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listenerclass>
</listener>
<! -- configure the configuration file of the loading class path -- >
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
  1. Inject the service object into the controller and call the method of the service object for testing
@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accoutService;

    /**
    * Query all data
    * @return
    */
    @RequestMapping("/findAll")
    public String findAll() {
        System.out.println("Performance layer: query all accounts...");
        accoutService.findAll();

        return "list";
    }
}

Chapter 4: Spring integrates MyBatis framework

1. Build and test MyBatis environment

  1. Write the configuration file of SqlMapConfig.xml and the core configuration file in the web project

    [external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uskgwpsp-1581341246581) (/ images / SSM% E6% 95% B4% E5% 90% 88-springmvc-spring-mybatis / image-20200210222275. PNG))

  2. Add annotation to the method of AccountDao interface and write SQL statement

    [external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-TU9WAq1E-1581341246584)(/images/SSM%E6%95%B4%E5%90%88-SpringMVC-Spring-Mybatis/image-20200210210239023.png))

  3. How to write tests

    [external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8saoffn95-1581341246587) (/ images / SSM% E6% 95% B4% E5% 90% 88-springmvc-spring-mybatis / image-20200210210321291. PNG))
    [external link image transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-GJ4OQ9LU-1581341246589)(/images/SSM%E6%95%B4%E5%90%88-SpringMVC-Spring-Mybatis/image-20200210210348078.png))

2. Spring integrates MyBatis framework

  1. Objective: to configure the content in SqlMapConfig.xml configuration file to applicationContext.xml configuration file
<!-- Configure connection pool objects -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql:///ssm" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>

<!-- To configure SqlSession Factory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<!-- Configuration scan dao Package -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.itcast.dao"/>
</bean>
  1. Add @ Repository annotation to the AccountDao interface

  2. Inject dao object into service for testing

  3. The code is as follows

@Repository
public interface AccountDao {
	@Insert( value = "insert into account (name,money) values (#{name},#{money})" )
	public void saveAccount( Account account );


	@Select( "select * from account" )
	public List<Account> findAll();
}





@Service( "accountService" )
public class AccountServiceImpl implements AccountService {
	@Autowired
	private AccountDao accountDao;
	public void saveAccount( Account account )
	{
	}


	public List<Account> findAll()
	{
		System.out.println( "Business layer: query all accounts..." );
		return(accountDao.findAll() );
	}
}





@Controller
@RequestMapping( "/account" )
public class AccountController {
	@Autowired
	private AccountService accoutService;
/**
 * Query all data
 * @return
 */
	@RequestMapping( "/findAll" )
	public String findAll()
	{
		System.out.println( "Performance layer: query all accounts..." );
		List<Account> list = accoutService.findAll();
		for ( Account account : list )
		{
			System.out.println( account );
		}
		return("list");
	}
}

  1. Configure declarative transaction management of Spring
    <!--To configure Spring Framework declarative transaction management-->
    <!--Configure transaction manager-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--Configure transaction notifications-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--To configure AOP Enhance-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
    </aop:config>
Published 3 original articles, won praise 0, visited 66
Private letter follow

Posted by Admiral S3 on Mon, 10 Feb 2020 07:44:49 -0800