今天咱們來說解一下SSM整合,感受整合這個比上一篇整合更費時,緣由在於本身不太熟悉MyBatis了,下午的時候惡補了一下,看了一下相關的文檔和PDF電子書,知識真的是你不用就會忘記的,之後仍是不能懈怠了,把本身不擅長的領域抓一下。html
爲何?怎麼作?去作?咱們今天圍繞着三個問題來展開話題的討論與內容的解說。java
1.0咱們爲何須要整合呢?mysql
解答:一個良好的框架可讓開發人員減輕從新創建解決複雜問題方案的負擔和精力;它能夠被擴展以進行內部的定製化;而且有強大的用戶社區來支持它。框架一般能很好的解決一個問題。然而,你的應用是分層的,可能每個層都須要各自的框架。web
好比:spring
Web層,就是MVC模式裏面的「C」(controller),負責控制業務邏輯層與表現層的交互,調用業務邏輯層,並將業務數據返回給表現層做組織表現。
Service層(就是業務邏輯層),負責實現業務邏輯。業務邏輯層以DAO層爲基礎,經過對DAO組件的正面模式包裝,完成系統所要求的業務邏輯。
DAO層,負責與持久化對象交互。該層封裝了數據的增、刪、查、改的操做。
PO,持久化對象。經過實體關係映射工具將關係型數據庫的數據映射成對象,很方便地實現以面向對象方式操做數據庫。
Spring的做用貫穿了整個中間層,將Web層、Service層、DAO層及PO無縫整合,其數據服務層用來存放數據。sql
同時給大家惡補一下,MyBatis的背景:數據庫
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.3.RELEASE</version> </dependency> <!--spring web jar 包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.3.RELEASE</version> </dependency> <!--spring-tx jar 包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.3.RELEASE</version> </dependency> <!--spring-ormjar 包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.3.RELEASE</version> </dependency> <!--spring-jdbcjar 包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.3.RELEASE</version> </dependency> <!--spring mvc jar 包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--commons-dncpjar 包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.1.1</version> </dependency> <!--c3p0jar 包--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!--struts2-spring-plugin jar 包--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.5.10</version> </dependency> <!--struts2 core 包--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.10</version> </dependency> <!--使用註解action--> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>2.5.10</version> </dependency> <!--hibernate-core jar 包--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.6.Final</version> </dependency> <!--jtajar 包--> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <!--mysql數據庫驅動--> <dependency> <groupId>org.wisdom-framework</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34_1</version> </dependency> <!--oraclejar 包--> <!--<dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.1.0</version> </dependency>--> <!--jstl jar包--> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-spec</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>org.apache.taglibs</groupId> <artifactId>taglibs-standard-impl</artifactId> <version>1.2.1</version> </dependency> <!--mybatis jar包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!--servlet api包--> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </resource> </resources> </build>
項目的架構圖:apache
大體上就是這樣的一個層次體系,養好一個好的習慣,你會在之後的日子裏輕鬆許多。api
beans:spring-mvc
package cn.mybatis.beans; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; /** * Created by accp on 2017/4/6. */ @Table public class Stock { @Id @GeneratedValue private Integer sid; @Column private String sname; @Column private String count; public Stock() { } public Stock(String sname, String count) { this.sname = sname; this.count = count; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } }
在這裏使用註解比較簡單一些,不用再建立一個xml文件了,前提是你懂得怎麼樣使用註解,分狀況使用。
實現類:StockDaoImpl
public class StockDaoImpl implements IStockDao { private SqlSessionFactory sqlSessionFactory; @Transactional public int login(Stock stock) { return sqlSessionFactory.openSession().getMapper(IStockDao.class).login(stock); } @Transactional public List<Stock> selectAll() { return sqlSessionFactory.openSession().getMapper(IStockDao.class).selectAll(); } public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } }
dao層:IStockDao
public interface IStockDao { /*登陸*/ int login(Stock stock); /*查詢所有*/ List<Stock> selectAll(); }
biz層:
package cn.mybatis.biz; import cn.mybatis.beans.Stock; import java.util.List; /** * Created by accp on 2017/4/6. */ public interface IStockBiz { /*登陸*/ int login(Stock stock); /*查詢所有*/ List<Stock> selectAll(); }
biz層的實現類:
package cn.mybatis.biz.impl; import cn.mybatis.beans.Stock; import cn.mybatis.biz.IStockBiz; import cn.mybatis.dao.IStockDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by accp on 2017/4/6. */ public class StockBizImpl implements IStockBiz { private IStockDao dao; @Transactional public int login(Stock stock) { return dao.login(stock); } @Transactional public List<Stock> selectAll() { return dao.selectAll(); } public IStockDao getDao() { return dao; } public void setDao(IStockDao dao) { this.dao = dao; } }
接下來就是action類:
package cn.mybatis.action; import cn.mybatis.beans.Stock; import cn.mybatis.biz.IStockBiz; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import java.util.List; public class LoginAction extends ActionSupport { //植入biz層的對象 private IStockBiz biz; //植入一個List<Stock>集合保存返回的數據 private List<Stock> list; @Override public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); String name = request.getParameter("name"); String count1 = request.getParameter("count"); Stock stock=new Stock(name,count1); int count = biz.login(stock); if(count>0){ list = biz.selectAll(); return SUCCESS; } return INPUT; } public List<Stock> getList() { return list; } public void setList(List<Stock> list) { this.list = list; } public IStockBiz getBiz() { return biz; } public void setBiz(IStockBiz biz) { this.biz = biz; } }
簡簡單單的幾個步驟咱們就把分層架構給搭建出來了,這也就進入了咱們項目的上升期,開始編寫xml文件了。
配置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> <!--別名--> <typeAliases> <typeAlias type="cn.mybatis.beans.Stock" alias="stock"></typeAlias> </typeAliases> <!--映射文件指定--> <mappers> <mapper resource="cn/mybatis/dao/IStockDao.xml"></mapper> </mappers> </configuration>
配置applicationContextmybatis.xml裏面的內容
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!--配置包掃描器--> <context:component-scan base-package="cn.mybatis"></context:component-scan> <!--配置數據源--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--注入jdbc--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--配置sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!--dao--> <bean id="stockDao" class="cn.mybatis.dao.impl.StockDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!--biz--> <bean id="service" class="cn.mybatis.biz.impl.StockBizImpl"> <property name="dao" ref="stockDao"></property> </bean> <!--action--> <bean id="loginAction" class="cn.mybatis.action.LoginAction"> <property name="biz" ref="service"></property> </bean> <!--事務管理器--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--註解驅動--> <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven> </beans>
配置IStockDao.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="cn.mybatis.dao.IStockDao"> <select id="login" resultType="int"> select count(*) from stock where sname=#{sname} and count=#{count} </select> <select id="selectAll" resultType="stock"> select * from stock </select> </mapper>
千萬不要忘了配置web.xml文件呦。
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Archetype Created Web Application</display-name> <!--設置讀取路徑--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContextmybatis.xml</param-value> </context-param> <!--配置監聽器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置filter--> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
struts.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.i18n.encoding" value="utf-8"></constant> <constant name="struts.devMode" value="false"></constant> <package name="default" extends="struts-default" namespace="/"> <action name="login" class="loginAction"> <result name="success">/success.jsp</result> <result name="input">/login.jsp</result> </action> </package> </struts>
寫到這裏,咱們先測試一下,防止有什麼差錯。
測試登陸是否成功:
@Test public void login(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContextmybatis.xml"); IStockBiz biz=(IStockBiz)ctx.getBean("service"); int count = biz.login(new Stock("北大", "10")); System.out.println(count); }
這就說明你的登陸通道沒有問題,咱們再來測試一下查詢的
@Test public void select(){ ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContextmybatis.xml"); IStockBiz biz=(IStockBiz)ctx.getBean("service"); List<Stock> list = biz.selectAll(); System.out.println(list.size()); }
咱們來看一下數據庫是不是兩條記錄:
數據庫的數據也是兩條,就說明咱們獲得的結果沒錯,如今咱們的登陸和查詢所有都沒有錯誤,接下來咱們就能夠把項目加到Tomcat裏了,
看看咱們使用頁面登陸和查詢有沒有什麼錯誤。
login.jsp頁面
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登陸頁面</title> </head> <body> <form action="login" method="POST"> <input name="name"/> <input name="count"> <input type="submit" value="登陸"> </form> </body> </html>
success.jsp
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>成功頁面</title> </head> <body> 歡迎登陸<br> 如下是查詢的內容: <c:forEach var="item" items="${list}"> ${item.sname} </c:forEach> </body> </html>
在這裏常常忘了少配置xml文件而出現各類各樣的問題,再加上不熟悉mybatis的書寫,寫這篇文章給我最大感觸就是,必定要塌下心來學習,有許多細節上的問題須要咱們注意,知識點的熟悉程度也要好,會解決問題。
其實寫這個項目過程當中一直報着一個空指針的錯誤,我看了很久,把代碼從上到下都看了一遍,多是以爲本身不會再小問題上犯錯誤就沒看建立實體類中的代碼檢查的那麼仔細,其實最後錯誤的引起點就是在我建立的一個構造上了,想省時間用快捷鍵生成的,反而給本身埋下了大坑,這個虧吃的不虧,我是這樣以爲的,這樣就會給本身提了個醒,小事要認真,我想我會一直記得。
很差意思,囉嗦了一下,接下來讓咱們把項目給啓動起來吧,看看效果。
效果出來了就放心了,這就說明咱們配置的沒有問題。
-----------------初學者本身的記錄