Maven搭建SpringMVC+Spring+MyBatis框架,將陸續集成新功能(github地址:https://github.com/jiangcaijun/ssm)html
##2017-01-22(maven + spring + spring MVC + mybatis項目)java
新建/conf/spring-mybatis.xmlmysql
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName"> <value>${jdbc_driverClassName}</value> </property> <property name="url"> <value>${jdbc_url}</value> </property> <property name="username"> <value>${jdbc_username}</value> </property> <property name="password"> <value>${jdbc_password}</value> </property> <!-- 鏈接池最大使用鏈接數 --> <property name="maxActive"> <value>20</value> </property> <!-- 初始化鏈接大小 --> <property name="initialSize"> <value>1</value> </property> <!-- 獲取鏈接最大等待時間 --> <property name="maxWait"> <value>60000</value> </property> <!-- 鏈接池最大空閒 --> <property name="maxIdle"> <value>20</value> </property> <!-- 鏈接池最小空閒 --> <property name="minIdle"> <value>3</value> </property> <!-- 自動清除無用鏈接 --> <property name="removeAbandoned"> <value>true</value> </property> <!-- 清除無用鏈接的等待時間 --> <property name="removeAbandonedTimeout"> <value>180</value> </property> <!-- 鏈接屬性 --> <property name="filters" value="config,wall,stat" /> <property name="connectionProperties"> <value>config.decrypt=true</value> </property> </bean> <!-- mybatis文件配置,掃描全部mapper文件 --> <!-- p:configLocation加載mybatis的配置文件 --> <!-- p:mapperLocations自動掃描model目錄中的映射xml文件,省去了在config中手工配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:conf/mybatis-config.xml" p:mapperLocations="classpath:cn/springmvc/mapper/*.xml" /><!-- configLocation爲mybatis屬性mapperLocations爲全部mapper --> <!-- spring與mybatis整合配置,掃描全部dao --> <!-- 對Dao 接口動態實現,須要知道接口在哪 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="cn.springmvc.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" /> <!-- 對數據源進行事務管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="list*" propagation="SUPPORTS" /> <tx:method name="check*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.ssm.service.*.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>
/conf/spring.xml (實現spring配置文件的掃描)git
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 引入jdbc配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 掃描文件(自動將servicec層注入) --> <context:component-scan base-package="com.ssm.service" /> </beans>
jdbc.properties(配置與數據庫的鏈接屬性,此處數據庫的密碼爲明文存在,後續將對其進行加密處理)github
jdbc_driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://localhost:3306/ssm_20170114?useUnicode=true&characterEncoding=utf-8 jdbc_username=root jdbc_password=admin
注意能夠利用Mybatis-Generator來生成Dao、Model、Mapping相關文件,以此減小工做量。 可參考連接:使用Mybatis-Generator自動生成Dao、Model、Mapping相關文件 - 李晨瑋 - 博客園(http://www.cnblogs.com/lichenwei/p/4145696.html)web
DROP TABLE IF EXISTS `user_t`; CREATE TABLE `user_t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(40) NOT NULL, `password` varchar(255) NOT NULL, `age` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
package com.ssm.model; /** * @Description: 用戶表 * @author jiangcaijun * @date 2017年01月20日 下午6:37:51 */ public class User { private Integer id; private String userName; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
package com.ssm.dao; import com.ssm.model.User; public interface UserMapper { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
<?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.ssm.dao.UserMapper"> <!-- 這裏用User而不是com.ssm.model.User(用它也是能夠的),是spring-mybatis別名 --> <resultMap id="BaseResultMap" type="User"> <id column="id" jdbcType="INTEGER" property="id" /> <result column="user_name" jdbcType="VARCHAR" property="userName" /> <result column="password" jdbcType="VARCHAR" property="password" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <sql id="Base_Column_List"> id, user_name, password, age </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from user_t where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user_t where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.ssm.model.User"> insert into user_t (id, user_name, password, age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.ssm.model.User"> insert into user_t <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="userName != null"> user_name, </if> <if test="password != null"> password, </if> <if test="age != null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="userName != null"> #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.ssm.model.User"> update user_t <set> <if test="userName != null"> user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.ssm.model.User"> update user_t set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
package com.ssm.service; import com.ssm.model.User; public interface UserService { public int insert(User user); /** * @Description: 根據id獲取user * @param @param id * @param @return 參數 * @return User 返回類型 */ public User getUser(int id); }
package com.ssm.service.impl; import com.ssm.dao.UserMapper; import com.ssm.model.User; import com.ssm.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service(value="userService") public class UserServiceImpl implements UserService { @Autowired private UserMapper usermapper; @Override public int insert(User user) { return usermapper.insert(user); } @Override public User getUser(int id) { return usermapper.selectByPrimaryKey(id); } }
package com.ssm.controller; import javax.annotation.Resource; import com.ssm.model.User; import com.ssm.service.UserService; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSONObject; @Controller @RequestMapping("/user") public class UserController { private static final Logger LOG = Logger.getLogger(UserController.class); @Autowired private UserService userService; /** * 用戶頁 * * @return */ @RequestMapping(value = "/user", method = RequestMethod.GET) public String userManager(Model model) { int id = 1; User user = userService.getUser(id); model.addAttribute("user", user); LOG.info(user.toString()); return "user/showUser"; } }
此處,也能夠採用 @Resource ,用@Resource後就沒必要使用@Autowired。以下:ajax
@Resource(name="userService") private UserService userService;
最好是將@Resource放在setter方法上,由於這樣更符合面向對象的思想,經過set、get去操做屬性,而不是直接去操做屬性。以下:spring
@Resource(name="userService") public void UserService(UserService userService) { this.userService = userService; }
在userController中添加以下兩個方法:sql
testAjax是模擬ajax請求,testPOJO是直接將POJO類轉爲json數據庫
/** * @Title: testAjax * @Description: post請求(測試用) * @param @param model * @param @return 參數 * @return String 返回類型 * @throws */ @RequestMapping(value = "/testAjax", method = RequestMethod.POST) @ResponseBody public String testAjax(Model model) { JSONObject jsonObject = new JSONObject(); jsonObject.put("id","數據拿到了"); return jsonObject.toString(); } /** * @Title: testPOJO * @Description: * @param @param model * @param @return 參數 * @return String 返回類型 * @throws */ @RequestMapping(value = "/testPOJO", method = RequestMethod.POST) @ResponseBody public User testPOJO(Model model) { int id = 1; User user = userService.getUser(id); return user; }
此時, http://localhost:8080/ssm_20170114/user/user 便可正常訪問了。框架結構以下(IDE由Eclipse轉爲idea):