IDEA realizes ssm integration and rapid development CRUD -- basic environment construction

Posted by Tandem on Mon, 21 Feb 2022 16:31:36 +0100

Project description

This project is a learning note document based on Shang Silicon Valley video, which is only used for learning, combing and summarizing relevant knowledge for later review, not for commercial purposes.

Project introduction

According to the basic frameworks such as Spring, Spring MVC and MyBatis, a simple addition, deletion, modification and query (i.e. CRUD) system is completed.
(Create Retrieve Update Delete)

Function point

1. Pagination
2. Data verification: jquery front-end verification + JSR303 back-end verification
3. ajax request
4. Rest style URI: use the verb of HTTP protocol request mode to indicate the operation on resources (GET (query), POST (add), PUT (modify), DELETE (DELETE))

Technical point

• basic framework ssm (spring MVC + Spring + mybatis)
• database MySQL
• front end framework - bootstrap can quickly build a simple and beautiful interface
• project dependency management Maven
• paging plug-in pagehelper
• reverse engineering - MyBatis Generator

Basic environment construction

1. Create a maven project (multi graph alert)

Create a new project
Select jdk1 eightWrite project name
Modify project structure

Changed to jdk1 eight

New web project

Configure the web project and set up the web Location of the XML configuration file

After configuration, click apply and ok

Note: a blue dot must appear on the webapp directory to indicate that the configuration of the web project is successful

Finally, set the character encoding in settings and automatically update the index dependency in idea

2. Import the jar package that the project depends on

It can be in maven central warehouse( Maven Repositor )Find the required jar package dependencies in

• spring: Spring JDBC, spring aspect oriented programming: Spring aspects
• springmvc: spring-webmvc
• mybatis: mybatis, mybatis integration spring adaptation package: mybatis spring
Code generator MBG: mybatis generator core, PageHelper, paging plug-in: PageHelper
• database connection pool, driver package: c3p0, database driver: MySQL connector Java
• others (jstl, servlet API, junit, etc.): json string: Jackson databind, JSR303, backend data verification: Hibernate validator, javax servlet-api,javax. servlet. JSP API, jstl, junit, spring test unit test: spring test

pom. The XML core configuration file code is as follows: (note that the packaging method is war package)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


    <!--Import project dependent jar package-->
    <!--springMVC,spring dependent jar package-->
        <!--return json String support-->
        <!--JSR303 Data verification support-->
        <!-- -->
        <!--Be careful not to lead the wrong package-->
        <!--spring Aspect oriented programming-->

        <!--mybatis dependent jar package-->
        <!--mybatis integration spring Adaptive package for-->
        <!-- mybatis-generator Code generator  MBG -->
        <!--introduce pageHelper Paging plug-in-->

        <!-- Database connection pool, driver, log -->


        <!--spring-test unit testing -->

3. Introduce bootstrap front-end framework

How to use the Bootstrap front-end framework?
1. First to Bootstrap official website Download related files

2. Copy and paste the downloaded file into the user-defined directory under the webapp of the project (such as static)

3. In index bootstrap style and js files are introduced into JSP pages (or pages that need to use the front-end framework)

Note: in jsp, JSTL tag library is often used to replace the code script <% Java statement% >, and EL expression is used to replace the expression script <% = expression% >
To use the jstl tag library, you need to first import the jar package of jstl (or introduce dependencies in pom.xml), and then use the taglib instruction to import the tag library (the code is as follows:)

	<!-- introduce Bootstrap style -->
    <link rel="stylesheet" href="${APP_PATH}/static/bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <!-- introduce jQuery (Bootstrap All JavaScript All plug-ins depend on jQuery,So it must be put in front) -->
    <script src="${APP_PATH}/static/bootstrap-3.4.1-dist/js/jquery-1.12.4.min.js"></script>
    <!-- introduce js Files, loading Bootstrap All JavaScript plug-in unit. You can also load only a single plug-in as needed. -->
    <script src="${APP_PATH}/static/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>

4. Finally, you can refer to the official Bootstrap documentation to complete the code editing

4. Write key configuration files for ssm integration


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""

    <!--1,start-up spring Container for-->
    <!--As soon as the project is started, it will be automatically loaded under the classpath spring of xxx.xml configuration file-->
    <!--to configure spring monitor-->

    <!--2,to configure springMVC The front-end controller intercepts all requests-->

    <!--3,Configure character encoding filter,Be sure to put it in front of all filters-->

    <!--4,use Rest Stylized URI(Filter),Change the page to normal get Transfer request to specified delete perhaps put request-->

Note: ApplicationContext xml,mybatis-config.xml,spring-mvc.xml (i.e. the configuration files of spring, mybatis and spring MVC) must be placed in the resources directory


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <!--springmvc The configuration file contains the control and configuration of website jump logic-->
    <!--Component scan-->
    <context:component-scan base-package="com.zuo" use-default-filters="false">
        <!--Scan only controller controller-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

    <!--Configure the view parser to facilitate the return of information from the page-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>

    <!--Two standard configurations-->
    <!--Static resource settings springmvc Requests that cannot be processed are handed over to tomcat Server processing-->
    <!--open SpringMVC Annotation driven, support springmvc More advanced features, JSR303 Effective and fast ajax,Mapping dynamic requests...-->


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <!--spring Configuration file, which is mainly related to business logic-->
    <!--spring The core point of the configuration file (data source, and mybatis Integration, transaction control)-->

    <!--Component scan main scan service and mapper(dao)-->
    <context:component-scan base-package="com.zuo">
        <!--exclude controller Scan of controller-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

    <!-- Associated database files - import external configuration files -->
    <context:property-placeholder location=""/>

    <!-- Database connection pool -->
        c3p0  Automatic operation (automatically load the configuration file and set it into 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"/>
        <!-- Not automatically after closing the connection commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- Get connection timeout -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- Number of retries when getting connection failed -->
        <property name="acquireRetryAttempts" value="2"/>

    <!-- Configuration and mybatis Integration of -->
    <!-- to configure SqlSessionFactory object -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- specify data source -->
        <property name="dataSource" ref="dataSource"/>
        <!-- appoint MyBaties Global profile location:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--appoint mybatis,mapper Location of mapping file-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>

    <!--Configure the scanner to mybatis The implementation of the interface is added to ioc In container-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--Scan all dao Interface implementation, added to ioc In container-->
        <property name="basePackage" value="com.zuo.dao"/>

    <!--Configure a batch sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/>

    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Specify the data source and control the data source -->
        <property name="dataSource" ref="dataSource" />

    <!--Open annotation based transactions, or use xml Transactions in configuration form (important transactions are generally configured)-->
        <!-- Pointcut expression-->
        <aop:pointcut id="txPoint" expression="execution(* com.zuo.service..*(..))"/>
        <!-- Configure transaction enhancements-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    <!--How to configure transaction enhancement and transaction entry-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <!--All methods are transaction methods-->
            <tx:method name="*"/>
            <!--with get All ways to start-->
            <tx:method name="get*" read-only="true"/>


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-// Config 3.0//EN"
    <!--mybatis Global profile for-->
    <!-- Configure hump naming rules-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    <!-- by bean Create aliases for all classes under the package (class lowercase)-->
        <package name="com.zuo.bean"/>

    <!--register pageHelper Paging plug-in-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--Paging parameter rationalization (not present)-1 Page, etc.)-->
            <property name="reasonable" value="true"/>

5) , using reverse engineering of mybatis to generate the corresponding bean, dao interface and mapper (mapper mapping file)

a) First, create SSM through SQLyog_ Crud database and tab_emp employee table and tab_dept department table and establish foreign key Association

USE ssm_crud;
	emp_name VARCHAR(255) NOT NULL DEFAULT '',
	gender CHAR(1),
	email VARCHAR(255),
	d_id INT,
	FOREIGN KEY (d_id) REFERENCES tab_dept(dept_id)
SELECT * FROM tab_emp;
SELECT * FROM tab_dept;

SELECT COUNT(*) FROM tab_dept;
	dept_name VARCHAR(255) NOT NULL DEFAULT ''
FROM tab_emp e
    LEFT JOIN tab_dept d ON e.`d_id`=d.`dept_id`
    WHERE emp_id = 1

b) Then in POM Register the code generator MBG of mybatis in XML (introduce related dependencies)
c) Create MBG under the project path XML configuration file

Code content

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-// MyBatis Generator Configuration 1.0//EN"

	<!--targetRuntime: Target operating environment-->
	<context id="DB2Tables" targetRuntime="MyBatis3">
		<!--suppressAllComments:When the property is true No comments are added to any generated elements.-->
			<property name="suppressAllComments" value="true" />
		<!-- Configure database connection information -->
		<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
			userId="root" password="hsp">

		<!--java Type resolution-->
			<property name="forceBigDecimals" value="false" />

		<!-- appoint javaBean Generated location targetProject: Target Engineering -->
		<javaModelGenerator targetPackage="com.zuo.bean"
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />

		<!--appoint sql Location where the mapping file is generated -->
		<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
			<property name="enableSubPackages" value="true" />

		<!-- appoint dao Location of interface generation, mapper Interface -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.zuo.dao" targetProject=".\src\main\java">
			<property name="enableSubPackages" value="true" />
		<!-- table Specify the build policy for each table -->
		<table tableName="tab_emp" domainObjectName="Employee"/>
		<table tableName="tab_dept" domainObjectName="Department"/>

Note the location of bean s, dao interfaces and mapper files generated by reverse engineering

6) , MBGTest test class code (generate corresponding bean, dao, and mapper)

package com.zuo.test;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

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

public class MBGTest {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);

Directory structure after generation (if there are many contents, the code will not be released, and it will be automatically generated after successful operation ~)

7),EmployeeMapper. Add joint query content in XML configuration file (you can query the information of employees and departments together)

  <!--The following is the new content (joint query) to query the information of employees and departments=========================================================-->
  <resultMap id="WithDeptResultMap" type="com.zuo.bean.Employee">
    <id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="gender" jdbcType="CHAR" property="gender" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="d_id" jdbcType="INTEGER" property="dId" />
    <!--Specifies the encapsulation of the Department field found by the joint query-->
    <association property="department" javaType="com.zuo.bean.Department">
      <id column="dept_id" property="deptId"/>
      <result column="dept_name" property="deptName"/>
  <sql id="WithDept_Column_List">
     e.emp_id, e.emp_name, e.gender,, e.d_id , d.dept_id, d.dept_name
  <!--List<Employee> selectByExampleWithDept(EmployeeExample example);
    Employee selectByPrimaryKeyWithDept(Integer empId);-->
  <!--Query employees with department information-->
  <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
    <if test="distinct">
    <include refid="WithDept_Column_List" />
    from tab_emp e
    left join tab_dept d on e.`d_id`=d.`dept_id`
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    <if test="orderByClause != null">
      order by ${orderByClause}
  <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">
    <include refid="WithDept_Column_List" />
    from tab_emp e
    left join tab_dept d on e.`d_id`=d.``
    where emp_id = #{empId,jdbcType=INTEGER}
  <!--Query employees without department information-->
  <select id="selectByExample" parameterType="com.zuo.bean.EmployeeExample" resultMap="BaseResultMap">
    <if test="distinct">
    <include refid="Base_Column_List" />
    from tab_emp
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    <if test="orderByClause != null">
      order by ${orderByClause}
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    <include refid="Base_Column_List" />
    from tab_emp
    where emp_id = #{empId,jdbcType=INTEGER}

Two abstract methods are added to the EmployeeMapper interface

  	List<Employee> selectByExampleWithDept(EmployeeExample example);

    Employee selectByPrimaryKeyWithDept(Integer empId);

Add the Department attribute and get() and set() methods in the Employee class

 private Department department;

    public Department getDepartment() {
        return department;

    public void setDepartment(Department department) {
        this.department = department;

8) Test mapper and build spring unit test environment (see whether spring container can automatically inject bean s and complete crud and other test operations)

Need to be in POM XML, and then @ ContextConfiguration specifies the location of the spring configuration file

<!--spring-test unit testing -->

MapperTest test class code (Note: in Department and Employee classes, we need to generate constructors with and without parameters)

package com.zuo.test;

import com.zuo.bean.Employee;
import com.zuo.dao.DepartmentMapper;
import com.zuo.dao.EmployeeMapper;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.UUID;

 * The recommended spring projects use spring unit tests, which can automatically inject the components we need
 * 1,Import springTest module
 * 2,@ContextConfiguration Specify the location of the spring configuration file
 * @RunWith(SpringJUnit4ClassRunner.class): Use the unit test module provided by spring to run the test
 * 3,Directly @ Autowired the components to be used
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class MapperTest {
    DepartmentMapper departmentMapper;
    EmployeeMapper employeeMapper;
    SqlSession sqlSession;

    public void testCRUD(){
        //Insert department information
        //departmentMapper.insertSelective(new Department(null, "development department");
        //departmentMapper.insertSelective(new Department(null, "test department");
        //Insert employee information
        employeeMapper.insertSelective(new Employee(null,"mary","m","",1));
        //You can use sqlSession to insert multiple employees in batch
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        for (int i = 0;i<1000;i++){
            String uuid = UUID.randomUUID().toString().substring(0, 5) + i;
            mapper.insertSelective(new Employee(null,uuid,"m",uuid + "",1));
        System.out.println("Batch completion");

Can be in ApplicationContext Configure a batch sqlSession in the XML configuration file (and then use @ Autowired to complete the automatic injection of sqlSession objects)

<!--Configure a batch sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/>

So far, our basic environment has been built. Now we can start writing CRUD code

Topics: Java Maven Ajax bootstrap SSM