Spring+SpringMVC+MyBatis (SSM) is often used in our project. This article mainly explains the integration of SSM using Intellij IDEA. The specific environment is as follows:
- Database: MySQL5.7
- Dependency management: Maven
- IDE: Intellij IDEA
- The JDK: 1.8
- Server: Tomcat 9
First, use Intellij IDEA to create Maven project. If you don’t know how to create Maven project, you can go to Baidu and Google first. There are many such tutorials on the Internet.
1. Create a table and insert data
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name CHAR(20) NOT NULL,
password CHAR(40) NOT NULL
)
ENGINE = InnoDB
AUTO_INCREMENT = 16
DEFAULT CHARSET = utf8;Copy the code
INSERT INTO user (id,name, password) VALUES (1,'A'.'123');
INSERT INTO user (id,name, password) VALUES (2,'B'.'456');Copy the code
2. Add Maven dependencies
<? 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. The demo < / groupId > < artifactId > SSM < / artifactId > <version> 1.0-snapshot </version> <packaging> WAR </packaging> <name>SSM</name> <description/> <properties> < spring version > 4.3.4. RELEASE < / spring. Version > < mybatis. Version > 3.4.2 < / mybatis version > <log4 j. version > 2.7 < /log4j.version> <junit.version>4.12</junit.version> <driver.version>5.1.40</driver.version> </properties> <dependencies> <! --Spring start--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-jdbc</artifactId>
<version>${spring.version}</version> </dependency> <! Springframework </groupId> <artifactId> Spring-oxm </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-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version> </dependency> <! --Spring end--> <! --AOP start--> <dependency> <groupId>aopalliance</ artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> The < version > 1.8.10 < / version > < / dependency > <! --AOP end--> <! <dependency> <groupId> Commons -fileupload</groupId> <artifactId> Commons -fileupload</artifactId> The < version > 1.3.2 < / version > < / dependency > <! End --> <! --json start--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> < version > 2.8.4 < / version > < / dependency > < the dependency > < groupId > com. Fasterxml. Jackson. Core < / groupId > < artifactId > Jackson - databind < / artifactId > < version > 2.8.4 < / version > < / dependency > <! --json end--> <! Mybatis </groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> The < version > 1.3.1 < / version > < / dependency > <! --mybatis end--> <! --log start--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId>
<version>${log4j.version}</version> </dependency> <! --log end--> <! <dependency> <groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <! -- Unit test end--> <! <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.40 < / version > < / dependency > <! -- database driver end--> <! Alibaba </groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency> <! --druid end--> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> < artifactId > maven -- the compiler plugin < / artifactId > < version > 3.6.1 < / version > < configuration > <source> 1.8 < /source> <target>1.8</target> </configuration> </plugin> <! --MBG--> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> The < version > 1.3.5 < / version > < configuration > < verbose >true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>Copy the code
The code is annotated so it’s easy to read. MyBatis Generator is a plug-in for generating MyBatis code, which will be used later. See the official documentation of MyBatis Generator for details
3. Configuration file
3.1 Mybatis Configuration file 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>Copy the code
3.2 Database configuration file database.properties
db.driver=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/mybatis? characterEncoding=UTF-8 db.user=root db.password=123456 db.maxActive=10 db.initialSize=2 db.minIdle=2 db.maxWait=60000 db.timeBetweenEvictionRunsMillis=3000 db.minEvictableIdleTimeMillis=300000 db.validationQuery=SELECT'x' FROM DUAL
db.testWhileIdle=true
db.testOnBorrow=false
db.testOnReturn=falseCopy the code
3.3 Spring configuration file application.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/spring-mybatis.xml"/>
</beans>Copy the code
Another configuration file, spring-Mybatis. XML, is introduced here with the import tag to facilitate project extension
<? 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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:properties/database.properties"/ > <! Datasource configuration --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <! -- driver --> <property name="driverClassName" value="${db.driver}"/ > <! -- database address --> <property name="url" value="${db.url}"/ > <! -- User name --> <property name="username" value="${db.user}"/ > <! -- Password --> <property name="password" value="${db.password}"/ > <! -- Maximum number of connection pools --> <property name="maxActive" value="${db.maxActive}"/ > <! -- Initializes the number of physical connections --> <property name="initialSize" value="${db.initialSize}"/ > <! -- Minimum number of connection pools --> <property name="minIdle" value="${db.minIdle}"/ > <! -- Maximum wait time --> <property name="maxWait" value="${db.maxWait}"/>
<property name="timeBetweenEvictionRunsMillis" value="${db.timeBetweenEvictionRunsMillis}"/>
<property name="minEvictableIdleTimeMillis" value="${db.minEvictableIdleTimeMillis}"/ > <! SQL --> <property name="validationQuery" value="${db.validationQuery}"/>
<property name="testWhileIdle" value="${db.testWhileIdle}"/ > <! ValidationQuery --> < Property name="testOnBorrow" value="${db.testOnBorrow}"/ > <! ValidationQuery --> <property name="testOnReturn" value="${db.testOnReturn}"/> </bean> <! Mybatis -config = Mybatis -config = Mybatis -config = Mybatis -config = Mybatis -config = Mybatis"sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> </bean> <! - Automatically scans all xxxxmapper. XML mapper interface files, so you don't need to manually configure Mpper mapping one by one, as long as mapper interface classes and mapper mapping files correspond to each other -> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.demo.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <! -- Transaction manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>Copy the code
3.4 SpringMVC configuration file 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: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/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"> <! < MVC :annotation-driven/> <! <context:component-scan base-package="com.demo.controller"/>
<context:component-scan base-package="com.demo.serviceImpl"/ > <! --> < MVC :resources mapping="/common/**" location="/common/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/image/**" location="/image/"/>
<mvc:resources mapping="/js/**" location="/js/"/ > <! Annotation mapper --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/ > <! Annotated adapter --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/ > <! -- View parser --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="contentType" value="text/html"/>
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/> </bean> <! --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <! -- Default encoding --> <property name="defaultEncoding" value="UTF-8"/ > <! -- Enabled to delay file parsing in order to catch file size exceptions --> <property name="resolveLazily" value="true"/ > <! -- Maximum file size --> <property name="maxUploadSize" value="209715200"/ > <! -- Maximum memory size --> <property name="maxInMemorySize" value="40960"/>
</bean>
</beans>Copy the code
3.5 Log4j configuration file log4j.xml
<? xml version="1.0" encoding="UTF-8"? > <Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>Copy the code
3.6 MyBatis Generator configuration file Generatorconfig.xml
<? 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> <! -- Database driver --> <classPathEntry location="C: / Users/Administrator/m2 / repository/mysql/mysql - connector - Java / 5.1.40 / mysql connector - Java - 5.1.40. Jar"/>
<context id="mybatis" targetRuntime="MyBatis3"> <! -- To prevent generated code from having many comments --> <commentGenerator> <property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="199498xy"> </jdbcConnection> <! The Java type parser should not enforce the use of the type object field BigDecimal, which is intended to make database DECIMAL and NUMERIC columns easy to handle --> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <! <javaModelGenerator targetPackage="com.demo.bean" targetProject="E:/workspace/java/project/SSM/src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/> </javaModelGenerator> <! <sqlMapGenerator targetPackage="mapper" targetProject="E:/workspace/java/project/SSM/src/main/resources">
<property name="enableSubPackages" value="true"/> </sqlMapGenerator> <! Generate the Dao class location --> <javaClientGeneratortype="XMLMAPPER" targetPackage="com.demo.dao" targetProject="E:/workspace/java/project/SSM/src/main/java">
<property name="enableSubPackages" value="true"/> </javaClientGenerator> <! --> <table tableName="user" domainObjectName="User"/>
</context>
</generatorConfiguration>Copy the code
Run the maven command on the CLI
mvn mybatis-generator:generateCopy the code
Generate the mapper. XML file for the User table, the bean, and the corresponding interface, as described below
<? 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.demo.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.demo.bean.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="CHAR" property="name" />
<result column="password" jdbcType="CHAR" property="password" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, name, password
</sql>
<select id="selectByExample" parameterType="com.demo.bean.UserExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from user
<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 user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.demo.bean.UserExample">
delete from user
<if test="_parameter ! = null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.demo.bean.User">
insert into user (id, name, password)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=CHAR}, #{password,jdbcType=CHAR})
</insert>
<insert id="insertSelective" parameterType="com.demo.bean.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id ! = null">
id,
</if>
<if test="name ! = null">
name,
</if>
<if test="password ! = null">
password,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id ! = null">
#{id,jdbcType=INTEGER},
</if>
<if test="name ! = null">
#{name,jdbcType=CHAR},
</if>
<if test="password ! = null">
#{password,jdbcType=CHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.demo.bean.UserExample" resultType="java.lang.Long">
select count(*) from user
<if test="_parameter ! = null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update user
<set>
<if test="record.id ! = null">
id = #{record.id,jdbcType=INTEGER},
</if>
<if test="record.name ! = null">
name = #{record.name,jdbcType=CHAR},
</if>
<if test="record.password ! = null">
password = #{record.password,jdbcType=CHAR},
</if>
</set>
<if test="_parameter ! = null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update user
set id = #{record.id,jdbcType=INTEGER},
name = #{record.name,jdbcType=CHAR},
password = #{record.password,jdbcType=CHAR}
<if test="_parameter ! = null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.demo.bean.User">
update user
<set>
<if test="name ! = null">
name = #{name,jdbcType=CHAR},
</if>
<if test="password ! = null">
password = #{password,jdbcType=CHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.demo.bean.User">
update user
set name = #{name,jdbcType=CHAR},
password = #{password,jdbcType=CHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>Copy the code
3.7 Web Configuration file 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_3_1.xsd"
version="3.1"> <! <welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <! -- Error jump page --> <error-page> <! -- Path error --> <error-code>404</error-code> <location>/error/404. JSP </location> </error-page> <error-page> <! --> <error-code>405</error-code> <location>/error/405. JSP </location> </error-page> <error-page> <! -- Internal error --> <error-code>500</error-code> <location>/error/500. JSP </location> </error-page> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </context-param> <! <filter> <filter-name>SpringEncodingFilter</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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>SpringEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code
4. Interfaces and classes
4.1 User. Java and userexample. Java under com.demo.bean
These two classes are generated by MBG
package com.demo.bean;
public class User {
private Integer id;
private String name;
private String password;
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 == null ? null : name.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) { this.password = password == null ? null : password.trim(); }}Copy the code
The Example class is used to construct complex filters
package com.demo.bean;
import java.util.ArrayList;
import java.util.List;
public class UserExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UserExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andPasswordIsNull() {
addCriterion("password is null");
return (Criteria) this;
}
public Criteria andPasswordIsNotNull() {
addCriterion("password is not null");
return (Criteria) this;
}
public Criteria andPasswordEqualTo(String value) {
addCriterion("password =", value, "password");
return (Criteria) this;
}
public Criteria andPasswordNotEqualTo(String value) {
addCriterion("password <>", value, "password");
return (Criteria) this;
}
public Criteria andPasswordGreaterThan(String value) {
addCriterion("password >", value, "password");
return (Criteria) this;
}
public Criteria andPasswordGreaterThanOrEqualTo(String value) {
addCriterion("password >=", value, "password");
return (Criteria) this;
}
public Criteria andPasswordLessThan(String value) {
addCriterion("password <", value, "password");
return (Criteria) this;
}
public Criteria andPasswordLessThanOrEqualTo(String value) {
addCriterion("password <=", value, "password");
return (Criteria) this;
}
public Criteria andPasswordLike(String value) {
addCriterion("password like", value, "password");
return (Criteria) this;
}
public Criteria andPasswordNotLike(String value) {
addCriterion("password not like", value, "password");
return (Criteria) this;
}
public Criteria andPasswordIn(List<String> values) {
addCriterion("password in", values, "password");
return (Criteria) this;
}
public Criteria andPasswordNotIn(List<String> values) {
addCriterion("password not in", values, "password");
return (Criteria) this;
}
public Criteria andPasswordBetween(String value1, String value2) {
addCriterion("password between", value1, value2, "password");
return (Criteria) this;
}
public Criteria andPasswordNotBetween(String value1, String value2) {
addCriterion("password not between", value1, value2, "password");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if(value instanceof List<? >) { this.listValue =true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); }}}Copy the code
4.2 Usermapper. Java under com.demo.dao
This DAO is also generated by MBG, which can help you to generate so much code, so young people can stay up late
package com.demo.dao;
import com.demo.bean.User;
import com.demo.bean.UserExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
long countByExample(UserExample example);
int deleteByExample(UserExample example);
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
List<User> selectByExample(UserExample example);
User selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
int updateByExample(@Param("record") User record, @Param("example") UserExample example);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}Copy the code
4.3 UserService. Java Interface under com.demo.service
The simple add, delete, and change methods are defined here
package com.demo.service;
import com.demo.bean.User;
import java.util.List;
public interface UserService {
void insertUser(User user);
void deleteUser(int id);
User findUserById(Integer id);
List<User> findAllUsers();
void updateUser(User user);
}Copy the code
UserServiceImpl. Java in 4.4 com.demo.serviceImpl
UserServiceImpl implements UserService, which operates on data by injecting UserMapper
package com.demo.serviceImpl;
import com.demo.bean.User;
import com.demo.bean.UserExample;
import com.demo.dao.UserMapper;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void insertUser(User user) {
userMapper.insert(user);
}
@Override
public void deleteUser(int id) {
UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo(id);
userMapper.deleteByExample(userExample);
}
@Override
public User findUserById(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
@Override
public List<User> findAllUsers() {
returnuserMapper.selectByExample(null); } @Override public void updateUser(User user) { userMapper.updateByPrimaryKey(user); }}Copy the code
Usercontroller.java in 4.5 com.demo.controller
A controller in MVC mode uses the injected UserService to complete related services
package com.demo.controller;
import com.demo.bean.User;
import com.demo.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/user")
public class UserController {
private static Logger logger = LogManager.getLogger();
@Autowired
private UserService userService;
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public User findUserById(@PathVariable("id") Integer id) {
User user = userService.findUserById(id);
logger.info(user.toString());
returnuser; }}Copy the code
5. Test
To deploy the project to your local Tomcat, open your Chrome and visit:
http://localhost:8080/user/1Copy the code
The browser accesses the server and the server returns json data successfully
Ok, by now the whole SSM integration process has been completed, as long as we can develop on this basis.
Project homepage: www.open-open.com/lib/view/ho…