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="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>com.zuo</groupId> <artifactId>ssm-crud</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <!--Import project dependent jar package--> <dependencies> <!--springMVC,spring dependent jar package--> <!--spring-webmvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--return json String support--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.1</version> </dependency> <!--JSR303 Data verification support--> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <!--Be careful not to lead the wrong package--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.17.Final</version> </dependency> <!--spring-jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--spring Aspect oriented programming--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--mybatis dependent jar package--> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <!--mybatis integration spring Adaptive package for--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> <!-- mybatis-generator Code generator MBG --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.4.0</version> </dependency> <!--introduce pageHelper Paging plug-in--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <!-- Database connection pool, driver, log --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!--servlet-api,jsp-api,jstl,junit--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--spring-test unit testing --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> </dependency> </dependencies> </project>
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:)
<% pageContext.setAttribute("APP_PATH",request.getContextPath()); %> <!-- 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
1),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"> <!--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--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <!--to configure spring monitor--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--2,to configure springMVC The front-end controller intercepts all requests--> <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*:spring-mvc.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> <!--3,Configure character encoding filter,Be sure to put it in front of all filters--> <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>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--4,use Rest Stylized URI(Filter),Change the page to normal get Transfer request to specified delete perhaps put request--> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HttpPutFormContentFilter</filter-name> <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class> </filter> <filter-mapping> <filter-name>HttpPutFormContentFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
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
2),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: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"> <!--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"/> </context:component-scan> <!--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"/> </bean> <!--Two standard configurations--> <!--Static resource settings springmvc Requests that cannot be processed are handed over to tomcat Server processing--> <mvc:default-servlet-handler/> <!--open SpringMVC Annotation driven, support springmvc More advanced features, JSR303 Effective and fast ajax,Mapping dynamic requests...--> <mvc:annotation-driven/> </beans>
3),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" 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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--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"/> </context:component-scan> <!-- Associated database files - import external configuration files --> <context:property-placeholder location="classpath:database.properties"/> <!-- 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"/> </bean> <!-- 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"/> </bean> <!--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"/> </bean> <!--Configure a batch sqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> <constructor-arg name="executorType" value="BATCH"/> </bean> <!-- 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" /> </bean> <!--Open annotation based transactions, or use xml Transactions in configuration form (important transactions are generally configured)--> <aop:config> <!-- Pointcut expression--> <aop:pointcut id="txPoint" expression="execution(* com.zuo.service..*(..))"/> <!-- Configure transaction enhancements--> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!--How to configure transaction enhancement and transaction entry--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!--All methods are transaction methods--> <tx:method name="*"/> <!--with get All ways to start--> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> </beans>
4),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> <!--mybatis Global profile for--> <!-- Configure hump naming rules--> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- by bean Create aliases for all classes under the package (class lowercase)--> <typeAliases> <package name="com.zuo.bean"/> </typeAliases> <!--register pageHelper Paging plug-in--> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!--Paging parameter rationalization (not present)-1 Page, etc.)--> <property name="reasonable" value="true"/> </plugin> </plugins> </configuration>
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
CREATE DATABASE ssm_crud; USE ssm_crud; CREATE TABLE tab_emp (emp_id INT PRIMARY KEY AUTO_INCREMENT, 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) )ENGINE=INNODB DEFAULT CHARSET=utf8 SELECT * FROM tab_emp; SELECT * FROM tab_dept; SELECT COUNT(*) FROM tab_emp; SELECT COUNT(*) FROM tab_dept; CREATE TABLE tab_dept (dept_id INT PRIMARY KEY AUTO_INCREMENT, dept_name VARCHAR(255) NOT NULL DEFAULT '' )ENGINE=INNODB DEFAULT CHARSET=utf8; SELECT * 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.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--targetRuntime: Target operating environment--> <context id="DB2Tables" targetRuntime="MyBatis3"> <!--suppressAllComments:When the property is true No comments are added to any generated elements.--> <commentGenerator> <property name="suppressAllComments" value="true" /> </commentGenerator> <!-- Configure database connection information --> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/ssm_crud" userId="root" password="hsp"> </jdbcConnection> <!--java Type resolution--> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- appoint javaBean Generated location targetProject: Target Engineering --> <javaModelGenerator targetPackage="com.zuo.bean" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!--appoint sql Location where the mapping file is generated --> <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- appoint dao Location of interface generation, mapper Interface --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.zuo.dao" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- table Specify the build policy for each table --> <table tableName="tab_emp" domainObjectName="Employee"/> <table tableName="tab_dept" domainObjectName="Department"/> </context> </generatorConfiguration>
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.io.File; 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); myBatisGenerator.generate(null); } }
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"/> </association> </resultMap> <sql id="WithDept_Column_List"> e.emp_id, e.emp_name, e.gender, e.email, e.d_id , d.dept_id, d.dept_name </sql> <!--List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId);--> <!--Query employees with department information--> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <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> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap"> select <include refid="WithDept_Column_List" /> from tab_emp e left join tab_dept d on e.`d_id`=d.`dept.id` where emp_id = #{empId,jdbcType=INTEGER} </select> <!--Query employees without department information--> <select id="selectByExample" parameterType="com.zuo.bean.EmployeeExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from tab_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tab_emp where emp_id = #{empId,jdbcType=INTEGER} </select> <!--==========================================================================================================-->
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 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> </dependency>
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 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:applicationContext.xml"}) public class MapperTest { @Autowired DepartmentMapper departmentMapper; @Autowired EmployeeMapper employeeMapper; @Autowired SqlSession sqlSession; @Test public void testCRUD(){ System.out.println(departmentMapper); System.out.println(employeeMapper); //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","mary@atguigu.com",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 + "@atguigu.com",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"/> </bean>
So far, our basic environment has been built. Now we can start writing CRUD code