Spring是一個開源框架,Spring是於2003 年興起的一個輕量級的Java 開發框架,由Rod Johnson 在其著做Expert One-On-One J2EE Development and Design中闡述的部分理念和原型衍生而來。它是爲了解決企業應用開發的複雜性而建立的。Spring使用基本的JavaBean來完成之前只可能由EJB完成的事情。然而,Spring的用途不只限於服務器端的開發。從簡單性、可測試性和鬆耦合的角度而言,任何Java應用均可以從Spring中受益。 簡單來講,Spring是一個輕量級的控制反轉(IOC)和麪向切面(AOP)的容器框架。java
###** SpringMVC** Spring MVC屬於SpringFrameWork的後續產品,已經融合在Spring Web Flow裏面。Spring MVC 分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定製。mysql
###** MyBatis** MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis 。MyBatis是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎全部的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。web
3.resources文件夾下建立資源文件spring
1.Maven引入須要的JAR包sql
jar包用途註釋有說明數據庫
<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日誌文件管理 --> <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> <!--這裏進行配置,後會自動的加載mapper.xml文件 :配置Maven 對resource文件 過濾 --> <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> <!--將編譯器的版本設定爲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> <!-- 基於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配置express
<?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 配置 --> <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配置apache
<?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配置spring-mvc
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 #<!-- 初始化鏈接大小 --> initialSize=0 #<!-- 鏈接池最大使用鏈接數量 --> maxActive=20 #<!-- 鏈接池最小空閒 --> minIdle=0 #<!-- 獲取鏈接最大等待時間 --> maxWait=60000 #<!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> minEvictableIdleTimeMillis=25200000 # <!-- 鏈接超時被回收 --> removeAbandonedTimeout=1800
5.log4j.properties配置tomcat
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 #文件大小到達指定尺寸的時候產生一個新的文件 log4j.appender.D = org.apache.log4j.RollingFileAppender #指定debug.log文件輸出地 log4j.appender.D.File = ${YHHSMS.root}/WEB-INF/logs/debug.log #指定每一個log.debug文件大小爲20k,建議設置成20M log4j.appender.D.MaxFileSize = 20MB #備份log文件最多爲10個,即debug.log10,以後還須要記錄日誌的話,將從新覆蓋debug.log,debug.log.1 ... log4j.appender.D.MaxBackupIndex=10 #true意思:將消息增長到指定文件中,false指將消息覆蓋指定的文件內容 log4j.appender.D.Append = true #消息輸出層次 log4j.appender.D.Threshold = DEBUG #消息輸出樣式 log4j.appender.D.layout = org.apache.log4j.PatternLayout #消息輸出格式 log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n #天天產生一個日誌文件 log4j.appender.E = org.apache.log4j.DailyRollingFileAppender #指定debug.log文件輸出地 log4j.appender.E.File = ${YHHSMS.root}/WEB-INF/logs/error.log #天天產生一個新的日誌 log4j.appender.E.DatePattern = "."yyyy-MM-dd #true意思:將消息增長到指定文件中,false指將消息覆蓋指定的文件內容 log4j.appender.E.Append = true #消息輸出層次 log4j.appender.E.Threshold = ERROR #消息輸出樣式 log4j.appender.E.layout = org.apache.log4j.PatternLayout #消息輸出格式 log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
6.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/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配置
<?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"> <!-- 配置數據源 --> <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}"/> <!-- 初始化鏈接大小 --> <property name="initialSize" value="${initialSize}" /> <!-- 鏈接池最大使用鏈接數量 --> <property name="maxActive" value="${maxActive}" /> <!-- 鏈接池最小空閒 --> <property name="minIdle" value="${minIdle}" /> <!-- 獲取鏈接最大等待時間 --> <property name="maxWait" value="${maxWait}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" /> <!-- 打開removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 鏈接超時被回收 --> <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 關閉abanded鏈接時輸出錯誤日誌 --> <property name="logAbandoned" value="true" /> <!-- 監控數據庫 --> <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> <!-- 配置事務管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 使用tx標籤配置的攔截器 實現事務注入 --> <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和generatorConfig.xml配置
PS:基於Maven的Mybatis_generator生成mapper,model 自行百度
關於插件方式生成mapper,model請參考http://www.javashuo.com/article/p-deabmdib-ct.html
實現簡單的用戶列表查詢
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>
效果如圖: