springmvc+spring+mybatis整合實例【轉】

開發(fā)環(huán)境:

System:Windows server 2003

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.

IDE:eclipse、MyEclipse 6.5

Database:MySQL

開發(fā)依賴庫:

JavaEE5、Spring 3.0.5、Mybatis 3.0.2、myBatis-spring-1.0.0-rc2

1、 首先新建一個WebProject 命名為ssi,新建項目時,使用JavaEE5的lib庫。然后手動添加需要的jar包,所需jar包如下:

2、 添加spring的監(jiān)聽及springMVC的核心Servlet,web.xml內(nèi)容,內(nèi)容如下:

org.springframework.web.context.ContextLoaderListenercontextConfigLocationclasspath:applicationContext-*.xmlspmvcorg.springframework.web.servlet.DispatcherServletspmvc*.doCharacterEncodingFilterorg.springframework.web.filter.CharacterEncodingFilterencodingutf-8CharacterEncodingFilter/*index.jsp

3、 在WEB-INF目錄中添加spmvc-servlet.xml,內(nèi)容如下:

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-3.0.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

4、 在src目錄下添加applicationContext-common.xml,內(nèi)容如下:

classpath:com/hoo/mapper/*.xml

上面的配置最先配置的是DataSource,這里采用的是jdbc的DataSource;

然后是SqlSessionFactoryBean,這個配置比較關鍵。SqlSessionFactoryBean需要注入DataSource數(shù)據(jù)源,其次還要設置configLocation也就是mybatis的xml配置文件路徑,完成一些關于mybatis的配置,如settings、mappers、plugin等;

如果使用MapperScannerPostProcessor模式,會自動將basePackage中配置的包路徑下的所有帶有@Mapper標注的Mapper(dao)層的接口生成代理,替代原來我們的Mapper實現(xiàn)。

5、AccountMapper接口內(nèi)容如下:

@Mapper("mapper")publicinterfaceAccountMapperextendsSqlMapper {publicListgetAllAccount();publicAccount getAccount();publicAccount getAccountById(String id);publicAccount getAccountByNames(String spring);

@Select("select * from account where username = #{name}")publicAccount getAccountByName(String name);publicvoidaddAccount(Account account);publicvoideditAccount(Account account);publicvoidremoveAccount(intid);

}

6、 實體類和account-resultmap.xml

privatestaticfinallongserialVersionUID = -7970848646314840509L;privateInteger accountId;privateInteger status;privateString username;privateString password;privateString salt;privateString email;privateInteger roleId;//getter、setter@OverridepublicString toString()

{returnthis.accountId + "#" +this.status + "#" +this.username +? "#" +this.password +? "#" +this.email +? "#" +this.salt + "#" +this.roleId;

}

account-resultmap.xml


"http://mybatis.org/dtd/mybatis-3-mapper.dtd">username, passwordinsert into account(account_id, status, username, password)

values(#{accountId}, #{status}, #{username}, #{password})select cast(random() * 10000 as Integer) a from #Tabinsert into account(account_id, status, username, password)

values(#{accountId}, #{status}, #{username}, #{password})update account set

status = #{status},

username = #{username},

password = #{password}

where account_id = #{accountId}delete from account where account_id = #{id}

7、 在src目錄中添加applicationContext-beans.xml內(nèi)容如下:

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-3.0.xsd">

這里配置bean對象,一些不能用annotation注解的對象就可以配置在這里

8、 在src目錄中添加mybatis.xml,內(nèi)容如下:



在這個文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的映射路徑(由于在applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,這里就不需要配置)等

9、 定義AccountDao接口及實現(xiàn)代碼,代碼如下:

publicinterfaceAccountDao{publicbooleanaddAccount(T entity)throwsDataAccessException;publicT getAccount(Integer id)throwsDataAccessException;publicList getList()throwsDataAccessException;

}

接口實現(xiàn)

importjava.util.List;importjavax.inject.Inject;importorg.springframework.dao.DataAccessException;importorg.springframework.stereotype.Repository;importorg.springframework.beans.factory.annotation.Autowired;importcom.hoo.dao.AccountDao;importcom.hoo.entity.*;importcom.hoo.mapper.*;importorg.springframework.beans.factory.annotation.Qualifier;

@SuppressWarnings("unchecked")

@Repository("accountDaoImpl")publicclassAccountDaoImplimplementsAccountDao{

@Autowired(required=false)

@Qualifier("mapper")privateAccountMapper mapper;publicbooleanaddAccount(T entity)throwsDataAccessException {booleanflag=false;try{

mapper.addAccount(entity);

flag=true;

}catch(DataAccessException e)

{

flag=false;throwe;

}returnflag;

}publicT getAccount(Integer id)throwsDataAccessException {

T entity=null;try{

entity=(T)mapper.getAccountById(String.valueOf(id));

}catch(DataAccessException e)

{throwe;? ? ? }returnentity;

}publicList getList()throwsDataAccessException {return(List)mapper.getAllAccount();

}

}

10、 服務層AccountBiz接口及實現(xiàn)代碼

接口:

publicinterfaceAccountBiz{publicbooleanaddAccount(T entity)throwsDataAccessException;publicT getAccount(Integer id)throwsDataAccessException;publicList getList()throwsDataAccessException;

}

實現(xiàn)代碼:

packagecom.hoo.biz.impl;importjava.util.List;importorg.springframework.dao.DataAccessException;importcom.hoo.biz.AccountBiz;importcom.hoo.entity.*;importjavax.inject.Inject;importcom.hoo.dao.*;importorg.springframework.stereotype.Service;importcom.hoo.exception.BizException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;

@Service("accountBizImpl")publicclassAccountBizImplimplementsAccountBiz{

@Autowired

@Qualifier("accountDaoImpl")privateAccountDaodao;publicbooleanaddAccount(T entity)throwsDataAccessException {if(entity==null){thrownewBizException(Account.class.getName()+"對象參數(shù)為empty!");

}returndao.addAccount(entity);

}publicT getAccount(Integer id)throwsDataAccessException {returndao.getAccount(id);

}publicList getList()throwsDataAccessException {returndao.getList();

}

}

11、 springMVC的控制器,AccountController代碼如下:

packagecom.hoo.controller;importjavax.inject.Inject;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.beans.factory.annotation.Autowired;importcom.hoo.biz.AccountBiz;importcom.hoo.entity.Account;importorg.springframework.beans.factory.annotation.Qualifier;

@Controller("accountController")

@RequestMapping("/account")publicclassAccountController {

@Autowired

@Qualifier("accountBizImpl")privateAccountBizbiz;

@RequestMapping("/add")publicString add(@RequestParam String username, @RequestParam String password, @RequestParam String status)

{

Integer stat=Integer.valueOf(status);

Account acc=newAccount(username,password,stat);

System.out.println(acc);

biz.addAccount(acc);return"redirect:/account/list.do";

}

@RequestMapping("/get")publicString get(Integer id,Model model)

{

System.out.println("###ID:"+id);

model.addAttribute(biz.getAccount(id));return"/show.jsp";

}

@RequestMapping("/list")publicString list(Model model)

{

model.addAttribute("list",biz.getList());return"/list.jsp";

}

@ExceptionHandler(Exception.class)publicString exception(Exception e,HttpServletRequest request)

{

request.setAttribute("exception", e);return"/error.jsp";

}

}

12、 基本頁面代碼

index.jsp

整合springmvc3.2+spring+mybatis3.2

查詢所有
添加
查詢

List.jsp

<%@ page language="java"import="java.util.*"pageEncoding="utf-8"%><%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>My JSP 'list.jsp' starting page-->id:${data.accountId }--name:${data.username }--password:

${data.password }


show.jsp

${account }

${account.username }#${account.accountId }

error.jsp

Exception:${exception }

詳細信息

<% Exception ex=(Exception)request.getAttribute("exception"); %>

<%ex.printStackTrace(new PrintWriter(out)); %>

13、 以上就基本上完成了整個Spring+SpringMVC+MyBatis的整合了。如果你想添加事務管理,得在applicationContext-common.xml中加入如下配置:


同時還需要加入aspectjweaver.jar這個jar包;

注意的是:Jdbc的TransactionManager不支持事務隔離級別,我在整個地方加入其它的TransactionManager,增加對transaction的隔離級別都嘗試失敗!

也許可以用于jpa、jdo、jta這方面的東西。

框架/平臺構成:

Maven+Springmvc + Mybatis + Shiro(權限)+ Tiles(模板) +ActiveMQ(消息隊列) + Rest(服務) + WebService(服務)+ EHcache(緩存) + Quartz(定時調(diào)度)+ Html5(支持PC、IOS、Android)

用戶權限系統(tǒng):

組織結構:角色、用戶、用戶組、組織機構;權限點:頁面、方法、按鈕、數(shù)據(jù)權限、分級授權

項目管理新體驗:

快速出原型系統(tǒng)、組件樹、版本控制、模塊移植、協(xié)同開發(fā)、實時監(jiān)控、發(fā)布管理

可持續(xù)集成:

所有組件可移植、可定制、可擴充,開發(fā)成果不斷積累,形成可持續(xù)發(fā)展的良性循環(huán)

支持平臺平臺:

Windows XP、Windows 7 、Windows 10 、 Linux 、 Unix

服務器容器:

Tomcat 5/6/7 、Jetty、JBoss、WebSphere 8.5

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,431評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,637評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,555評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,900評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,629評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,976評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,976評論 3 448
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,139評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,686評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,411評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,641評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,129評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,820評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,233評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,567評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,362評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,604評論 2 380

推薦閱讀更多精彩內(nèi)容