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

開發環境:

System:Windows server 2003

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.

IDE:eclipse、MyEclipse 6.5

Database:MySQL

開發依賴庫:

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

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

2、 添加spring的監聽及springMVC的核心Servlet,web.xml內容,內容如下:

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,內容如下:

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,內容如下:

classpath:com/hoo/mapper/*.xml

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

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

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

5、AccountMapper接口內容如下:

@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內容如下:

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,內容如下:



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

9、 定義AccountDao接口及實現代碼,代碼如下:

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

}

接口實現

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接口及實現代碼

接口:

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

}

實現代碼:

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()+"對象參數為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(定時調度)+ Html5(支持PC、IOS、Android)

用戶權限系統:

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

項目管理新體驗:

快速出原型系統、組件樹、版本控制、模塊移植、協同開發、實時監控、發布管理

可持續集成:

所有組件可移植、可定制、可擴充,開發成果不斷積累,形成可持續發展的良性循環

支持平臺平臺:

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

服務器容器:

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容