Spring
Spring is an open source framework. Spring is a lightweight Java development framework that emerged in 2003. It is derived from some concepts and prototypes elaborated by Rod Johnson in his book Expert One-On-One J2EE Development and Design. It is created to solve the complexity of enterprise application development. Spring uses basic JavaBean s to do things that previously could only be done by EJB s. However, Spring's use is not limited to server-side development. From the point of view of simplicity, testability and loose coupling, any Java application can benefit from Spring. In short, Spring is a lightweight control inversion (IoC) and Aspect-Oriented (AOP) container framework.
SpringMVC
Spring MVC is a follow-up product of Spring FrameWork and has been integrated into Spring Web Flow. Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, making them easier to customize.
MyBatis
MyBatis was originally an open source project of apache, iBatis, which was moved from apache software foundation to google code in 2010 and renamed MyBatis. MyBatis is a Java-based persistence framework. The persistence framework provided by iBATIS includes SQL Maps and Data Access Objects (DAO) MyBatis, which eliminates manual settings of almost all JDBC codes and parameters as well as retrieval of result sets. MyBatis uses simple XML or annotations to configure and map interfaces and Java POJOs (Plain Old Java Objects, common Java objects) into records in the database.
Construction of Development Environment
- jdk1.7 and above
- apache-maven-3.3.9
- apache-tomcat-8.0.9
- Development tool IDEA
Integrating SSM Framework
- New maven Project, catalogue as follows:
- Establishing MVC Layering
3. Create resource files under the Resources folder
Detailed configuration
1.Maven introduces the required JAR packages Notes on the use of jar packages are explained
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>ssmDemo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssmDemo</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.6.RELEASE</spring.version> </properties> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-context</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>org.springframework</groupId> <artifactId>spring-dao</artifactId> <version>2.0.8</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.26</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- log4j Log file management --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> </dependencies> <build> <finalName>ssmDemo</finalName> <!--Configuration here,Later automatic loading mapper.xml file :To configure Maven Yes resource File filtering --> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <!--Set the compiler version to 1.7 --> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <!-- Be based on Maven: MyBatis Generator --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> </project>
2.web.xml configuration
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>ssmDemo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ssmDemo</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <context-param> <param-name>webAppRootKey</param-name> <param-value>ssmDemo.root</param-value> </context-param> <!-- Log4j To configure --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>10000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> </web-app>
3.applicationContext.xml configuration
<?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="spring-mvc.xml" /> <import resource="spring-mybatis.xml"/> </beans>
4.dataSource.properties configuration
driverClassName=com.mysql.jdbc.Driver jdbc.connectionURL=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC jdbc.username=root jdbc.password=123456 #Initialize connection size - & gt; initialSize=0 #The maximum number of connections used in connection pool - & gt; maxActive=20 #The smallest idle connection pool - & gt; minIdle=0 #Get the maximum connection waiting time - & gt; maxWait=60000 #Configure a minimum lifetime of a connection in the pool in milliseconds - & gt; minEvictableIdleTimeMillis=25200000 # Connection timeout is recycled - & gt; removeAbandonedTimeout=1800
5.log4j.properties configuration
log4j.rootLogger=info , stdout, D, E log4j.logger.java.sql.Connection = DEBUG log4j.logger.java.sql.Statement = DEBUG log4j.logger.java.sql.PreparedStatement = DEBUG log4j.logger.java.sql.ResultSet = DEBUG log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n #Generate a new file when the file size reaches the specified size log4j.appender.D = org.apache.log4j.RollingFileAppender #Specify the debug.log file output location log4j.appender.D.File = ${YHHSMS.root}/WEB-INF/logs/debug.log #Specify the size of each log.debug file as 20k. It is recommended to set it to 20M. log4j.appender.D.MaxFileSize = 20MB #Backup log files are up to 10, debug.log10. If you need to log later, debug.log,debug.log.1 will be overwritten. log4j.appender.D.MaxBackupIndex=10 #true means: To add a message to a specified file, false means to overwrite the specified file content with a message. log4j.appender.D.Append = true #Message Output Level log4j.appender.D.Threshold = DEBUG #Message Output Style log4j.appender.D.layout = org.apache.log4j.PatternLayout #Message Output Format log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n #Generate a log file every day log4j.appender.E = org.apache.log4j.DailyRollingFileAppender #Specify the debug.log file output location log4j.appender.E.File = ${YHHSMS.root}/WEB-INF/logs/error.log #Generate a new log every day log4j.appender.E.DatePattern = "."yyyy-MM-dd #true means: To add a message to a specified file, false means to overwrite the specified file content with a message. log4j.appender.E.Append = true #Message Output Level log4j.appender.E.Threshold = ERROR #Message Output Style log4j.appender.E.layout = org.apache.log4j.PatternLayout #Message Output Format log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
6.spring-mvc.xml configuration
<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 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-4.2.xsd"> <!-- driven --> <mvc:annotation-driven/> <!-- data config --> <context:property-placeholder location="classpath:dataSource.properties"/> <!-- scan --> <context:component-scan base-package="com.test.ssmDemo"/> </beans>
7.spring-mybatis.xml configuration
<?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 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-4.1.xsd"> <!-- Configuring data sources --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.connectionURL}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- Initialize connection size --> <property name="initialSize" value="${initialSize}" /> <!-- Maximum number of connections used in connection pool --> <property name="maxActive" value="${maxActive}" /> <!-- Connection pool minimum idleness --> <property name="minIdle" value="${minIdle}" /> <!-- Get the maximum connection waiting time --> <property name="maxWait" value="${maxWait}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- Configure the minimum lifetime of a connection in the pool in milliseconds --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" /> <!-- open removeAbandoned function --> <property name="removeAbandoned" value="true" /> <!-- Connection timeout recovery --> <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- Close abanded Output error log at connection time --> <property name="logAbandoned" value="true" /> <!-- Monitoring database --> <property name="filters" value="mergeStat" /> </bean> <!-- sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:com/test/ssmDemo/mapper/*.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.test.ssmDemo.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- Configuration transaction management --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- Use tx Interceptor of Label Configuration for Transaction Injection --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="register*" propagation="REQUIRED" /> <tx:method name="upd*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.test.ssmDemo.service.impl.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
8.generator.properties and generatorConfig.xml configuration
PS: Maven-based Mappers_generator generates mapper,model Baidu
Refer to https://my.oschina.net/u/2963821/blog/760035 for plug-in generation mapper.
Database Design
Coding design
Implementing Simple User List Query
1.Controller
package com.test.ssmDemo.controller; import com.test.ssmDemo.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; public static final Logger logger; static { logger = LoggerFactory.getLogger(UserController.class); } @RequestMapping(value = "/getUserList", method = RequestMethod.GET) public void getUserList() { logger.info(userService.getUserList().toString()); } }
2.Service
package com.test.ssmDemo.controller; import com.test.ssmDemo.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; public static final Logger logger; static { logger = LoggerFactory.getLogger(UserController.class); } @RequestMapping(value = "/getUserList", method = RequestMethod.GET) public void getUserList() { logger.info(userService.getUserList().toString()); } }
3.ServiceImpl
package com.test.ssmDemo.service.impl; import com.test.ssmDemo.mapper.UserMapper; import com.test.ssmDemo.model.User; import com.test.ssmDemo.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 List<User> getUserList() { return userMapper.selectUserList(); } }
4.UserMapper.java
package com.test.ssmDemo.mapper; import com.test.ssmDemo.model.User; import java.util.List; public interface UserMapper { int deleteByPrimaryKey(String userId); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(String userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); List<User> selectUserList(); }
5.UserMapper.xml
<?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.test.ssmDemo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.test.ssmDemo.model.User"> <id column="user_id" property="userId" jdbcType="VARCHAR"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="INTEGER"/> <result column="tel" property="tel" jdbcType="VARCHAR"/> </resultMap> <sql id="Base_Column_List"> user_id, name, age, tel </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String"> select <include refid="Base_Column_List"/> from user where user_id = #{userId,jdbcType=VARCHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.String"> delete from user where user_id = #{userId,jdbcType=VARCHAR} </delete> <insert id="insert" parameterType="com.test.ssmDemo.model.User"> insert into user (user_id, name, age, tel) values (#{userId,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{tel,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.test.ssmDemo.model.User"> insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="userId != null"> user_id, </if> <if test="name != null"> name, </if> <if test="age != null"> age, </if> <if test="tel != null"> tel, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="userId != null"> #{userId,jdbcType=VARCHAR}, </if> <if test="name != null"> #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> <if test="tel != null"> #{tel,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.test.ssmDemo.model.User"> update user <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> <if test="tel != null"> tel = #{tel,jdbcType=VARCHAR}, </if> </set> where user_id = #{userId,jdbcType=VARCHAR} </update> <update id="updateByPrimaryKey" parameterType="com.test.ssmDemo.model.User"> update user set name = #{name,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER}, tel = #{tel,jdbcType=VARCHAR} where user_id = #{userId,jdbcType=VARCHAR} </update> <select id="selectUserList" resultType="com.test.ssmDemo.model.User"> SELECT user_id AS userId, name, age, tel FROM user; </select> </mapper>
Finally get the project running
The effect is as follows: