代碼地址:https://pan.baidu.com/s/18dyR6GDcsbsF5CDd3tJ85g 密碼:q7je
SSM:spring + spring mvc + mybatis
可以先看看我之前寫的spring mvc怎么搭以及怎么使用Mybatis-Generator自動(dòng)生成Dao贯吓、Model層相關(guān)代碼玖雁,再看這篇,傳送門:
IntelliJ IDEA搭建最簡(jiǎn)單的Spring MVC項(xiàng)目
IntelliJ IDEA下Spring MVC數(shù)據(jù)庫(kù)配置與增刪改查開發(fā)
使用Mybatis-Generator自動(dòng)生成Dao李破、Model層相關(guān)代碼
與之相關(guān)的就不再寫了钓简。
1 新建工程芜壁,并完善目錄結(jié)構(gòu)與前面兩篇文章一樣
目錄結(jié)構(gòu)多了個(gè)service,用以放業(yè)務(wù)邏輯疏日。
2 添加依賴包
pom.xml中依賴包加入:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!-- spring版本號(hào) -->
<spring.version>5.0.5.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 數(shù)據(jù)庫(kù) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
<scope>runtime</scope>
</dependency>
<dependency>
<!--jdbc連接池-->
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- DAO: MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- Servlet web -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Gson-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Spring -->
<!-- Spring核? -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- Spring DAO層 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- Spring web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!-- Spring test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
</dependencies>
3 添加各種配置文件
數(shù)據(jù)源
在resources下面新建jdbc.properties文件盈滴。
這個(gè)文件用以配置jdbc數(shù)據(jù)源以及數(shù)據(jù)連接池的各種參數(shù)涯肩,單獨(dú)放到文件便于修改。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/cmtable?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
#最大連接數(shù)
maxPoolSize=20
#最小連接數(shù)
minPoolSize=10
#連接超時(shí)時(shí)間
checkoutTimeout=60000
#失敗重連次數(shù)
acquireRetryAttempts=3
mybatis-config.xml
在resources下面新建mybatis-config.xml巢钓,作為MyBatis的全局配置文件病苗。
<?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>
<!--配置全局屬性-->
<settings>
<!-- 使?jdbc的getGeneratedKeys獲取數(shù)據(jù)庫(kù)?增主鍵值 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 使?列別名替換列名 默認(rèn):true -->
<setting name="useColumnLabel" value="true" />
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
這個(gè)作為MyBatis的全局配置文件,還有很多參數(shù)可以設(shè)置竿报,這里不細(xì)講铅乡。
掃描 sql 配置?件:mapper 需要的 xml ?件
在resources文件夾下面新建mapper目錄继谚,用以放置那些對(duì)應(yīng)的xml文件烈菌。
applicationContext.xml Spring全局配置文件
在resources下面新建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"
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/tx http://www.springframework.org/schema/tx/springtx.xsd">
<!--配合MyBatis-->
<!--配置數(shù)據(jù)庫(kù)參數(shù)-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--數(shù)據(jù)庫(kù)連接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--配置連接池屬性-->
<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連接池私有屬性-->
<property name="maxPoolSize" value="${maxPoolSize}"/>
<property name="minPoolSize" value="${minPoolSize}"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="${checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
</bean>
<!-- 配置 SqlSessionFactory 對(duì)象,spring和MyBatis完美整合花履,不需要mybatis的配置映射文件-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入數(shù)據(jù)庫(kù)連接池-->
<property name="dataSource" ref="dataSource"/>
<!-- 配置 MyBaties 全局配置?件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 掃描 model 包 使?別名 -->
<property name="typeAliasesPackage" value="com.cm.model"/>
<!-- 掃描 sql 配置?件:mapper 需要的 xml ?件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置掃描 dao 接?包芽世, 動(dòng)態(tài)實(shí)現(xiàn) dao 接?, 注?到 Spring 容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注? sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描 dao 接?包 -->
<property name="basePackage" value="com.cm.dao"/>
</bean>
<!--spring-service-->
<!-- 掃描 service 包下所有使?注解的類型 -->
<context:component-scan base-package="com.cm.service"/>
<!-- 配置事務(wù)管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注?數(shù)據(jù)庫(kù)連接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
mvc-dispatcher.xml
在resources下面新建mvc-dispatcher.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:p="http://www.springframework.org/schema/p"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- controller掃描器 -->
<context:component-scan base-package="com.cm.controller"/>
<!-- 配置注解驅(qū)動(dòng) -->
<mvc:annotation-driven/>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前綴-->
<property name="prefix" value="/WEB-INF/views/"/>
<!--后綴-->
<property name="suffix" value=".jsp"/>
</bean>
<!--靜態(tài)資源默認(rèn)servlet配置
(1)加?對(duì)靜態(tài)資源的處理: js,gif,png
(2)允許使?"/"做整體映射
-->
<mvc:default-servlet-handler/>
</beans>
web.xml
與前面文章一模一樣。
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--Spring MVC 配置 并添加監(jiān)聽-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 字符過(guò)濾器 傳值亂碼-->
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置前端控制器 進(jìn)行請(qǐng)求分發(fā) DispatcherServlet本質(zhì)也是一個(gè)Servlet -->
<servlet>
<!--名字可以自定義-->
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc-dispatcher.xml</param-value>
</init-param>
<!--標(biāo)記容器啟動(dòng)的時(shí)候就啟動(dòng)這個(gè)servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!--攔截所有-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
好了妹卿,所有的配置文件都弄完了旺矾!
4 開發(fā)
建表。
使用之前文章里面說(shuō)的方法自動(dòng)生成Model和Dao以及對(duì)應(yīng)的xml代碼夺克。
看看生成的代碼箕宙,UserModel.java與前面類似,跳過(guò)铺纽。
其他的只是能參考柬帕,在這個(gè)基礎(chǔ)上改,畢竟生成的有的接口不符合我們的想法狡门。
package com.cm.dao;
import com.cm.model.UserModel;
import java.util.List;
public interface UserDao {
List<UserModel> getAllUsers();
UserModel getUser(String id);
boolean addUser(UserModel userModel);
boolean updateUser(String id, String name);
boolean deleteUser(String id);
}
MyBatis有個(gè)好處就是我們不用自己寫實(shí)現(xiàn)陷寝,只需要配置對(duì)應(yīng)的xml為其提供sql語(yǔ)句就行,在resources下的mapper文件夾下面新建UserDao.xml其馏。模仿我們生成的xml進(jìn)行修改凤跑。
<?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.cm.dao.UserDao">
<select id="getAllUsers" resultType="UserModel">
select * from user
</select>
<select id="getUser" resultType="UserModel">
select * from user where id = #{id}
</select>
<insert id="addUser">
<!--ignore忽略自動(dòng)增長(zhǎng)的主鍵id-->
insert ignore into user (name, age) values (#{id}, #{name})
</insert>
<update id="updateUser">
update user set name=#{name} where id=#{id}
</update>
<delete id="deleteUser" parameterType="String">
delete from user where id=#{id}
</delete>
</mapper>
其實(shí)就是一堆sql語(yǔ)句,namespace表示對(duì)應(yīng)的類叛复。id對(duì)應(yīng)方法名仔引,#{name}表示傳入的參數(shù)鹏控。parameterType為入?yún)㈩愋停梢允÷浴?/p>
service層
在service中新建UserService肤寝,放置業(yè)務(wù)邏輯代碼当辐。可以這么理解鲤看,Dao顆粒度比較小缘揪,基本操作,但是service顆粒度比較大义桂,放業(yè)務(wù)邏輯操作找筝。
package com.cm.service;
import com.cm.dao.UserDao;
import com.cm.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
public List<UserModel> getAllUsers(){
return userDao.getAllUsers();
}
public UserModel getUser(String id) {
return userDao.getUser(id);
}
boolean addUser(UserModel userModel) {
return userDao.addUser(userModel);
}
boolean updateUser(String id, String name) {
return userDao.updateUser(id, name);
}
boolean deleteUser(String id) {
return userDao.deleteUser(id);
}
}
學(xué)習(xí)階段就不寫太大的業(yè)務(wù)邏輯了。
說(shuō)幾個(gè):
(1) @Service 標(biāo)記為service慷吊,這樣就能被Spring掃描到袖裕。
(2)@Transactional,我們前面配置文件開啟了事務(wù)處理溉瓶。業(yè)務(wù)邏輯需要進(jìn)行事務(wù)處理急鳄。
標(biāo)注在類前:標(biāo)示類中所有方法都進(jìn)行事務(wù)處理
標(biāo)注在接口、實(shí)現(xiàn)類的方法前:標(biāo)示方法進(jìn)行事務(wù)處理
(3)@Autowired這個(gè)前面文章講過(guò)了堰酿,自動(dòng)注入疾宏。
Controller 層
在controller下面新建UserController.java。內(nèi)容就不全寫了触创,以兩個(gè)為例坎藐。其他類似。
package com.cm.controller;
import com.cm.model.UserModel;
import com.cm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(value="getAllUsers",method = RequestMethod.GET)
@ResponseBody
public List<UserModel> getAllUsers() {
List<UserModel> userModels = userService.getAllUsers();
return userModels;
}
@RequestMapping(value="getUser",method = RequestMethod.GET)
@ResponseBody
public UserModel getUser(String id) {
UserModel userModel = userService.getUser(id);
return userModel;
}
}
5 測(cè)試
配置Tomcat哼绑,方法前面說(shuō)過(guò)了岩馍。表中插入一些數(shù)據(jù)。用瀏覽器或者postman訪問抖韩。
http://localhost:8080/user/getAllUsers 結(jié)果如下:
http://localhost:8080/user/getUser?id=2 結(jié)果如下:
6 打包
點(diǎn)擊左下角蛀恩,在彈出的地方點(diǎn)擊右邊的Maven Projects,然后展開Lifecycle帽蝶,雙擊package赦肋。然后就能在webapp下面看見war包,把war包放到tomcat下面的webapp里面励稳,啟動(dòng)tomcat就能訪問佃乘。注意這樣訪問要加上artifactid,示例:http://localhost:8080/SSM/user/getAllUsers
【SSM框架從零開始】系列文章鏈接:
IntelliJ IDEA搭建最簡(jiǎn)單的Spring MVC項(xiàng)目
IntelliJ IDEA下Spring MVC數(shù)據(jù)庫(kù)配置與增刪改查開發(fā)
使用Mybatis-Generator自動(dòng)生成Dao驹尼、Model層相關(guān)代碼
IntelliJ IDEA搭建SSM框架