MyBatis3整合Spring三、SpringMVC3

開發環境: javascript

System:Windows html

WebBrowser:IE6+、Firefox3+ java

JavaEE Server:tomcat5.0.2.八、tomcat6 mysql

IDE:eclipse、MyEclipse 8 web

Database:MySQL spring

開發依賴庫: sql

JavaEE五、Spring 3.0.五、Mybatis 3.0.四、myBatis-spring-1.0、junit4.8.2 數據庫

Email:hoojo_@126.com apache

Blog:http://blog.csdn.net/IBM_hoojo 瀏覽器

http://hoojo.cnblogs.com/

百度文庫:http://wenku.baidu.com/view/34559702a6c30c2259019e4e.html

一、 首先新建一個WebProject 命名爲MyBatisForSpring,新建項目時,使用JavaEE5的lib庫。而後手動添加須要的jar包,所需jar包以下:

clip_image002

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

<!-- 加載Spring容器配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
   
<!-- 設置Spring容器加載配置文件路徑 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>
 
   
<!-- 配置Spring核心控制器 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
 
   
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
 
   
<!-- 解決工程編碼過濾器 -->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

三、 在WEB-INF目錄中添加dispatcher.xml,內容以下:

<?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-3.0.xsd"
<!-- 註解探測器 -->
<context:component-scan base-package="com.hoo"/>
 
   
<!-- annotation默認的方法映射適配器 -->
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
 
   
<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
</beans>

四、 在src目錄下添加applicationContext-common.xml,內容以下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "
 
   
<!-- 配置DataSource數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://10.0.0.131:3306/ash2"/>
<property name="username" value="dev"/>
<property name="password" value="dev"/>
</bean>
 
   
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
<!-- mapper和resultmap配置路徑 -->
<property name="mapperLocations">
<list>
<!-- 表示在com.hoo.resultmap包或如下全部目錄中,以-resultmap.xml結尾全部文件 -->
<value>classpath:com/hoo/resultmap/**/*-resultmap.xml</value>
<value>classpath:com/hoo/entity/*-resultmap.xml</value>
<value>classpath:com/hoo/mapper/**/*-mapper.xml</value>
</list>
</property>
</bean>
 
   
<!-- 單獨配置一個Mapper; 這種模式就是得給每一個mapper接口配置一個bean -->
<!-- 
 <bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
 <property name="mapperInterface" value="com.hoo.mapper.AccountMapper" />
 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
 </bean> 
 
 <bean id="companyMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
 <property name="mapperInterface" value="com.hoo.mapper.CompanyMapper" />
 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
 </bean>
 -->
 
   
<!-- 經過掃描的模式,掃描目錄在com/hoo/mapper目錄下,全部的mapper都繼承SqlMapper接口的接口, 這樣一個bean就能夠了 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hoo.mapper"/>
<property name="markerInterface" value="com.hoo.mapper.SqlMapper"/>
</bean>
</beans>

上面的配置最早配置的是DataSource,這裏採用的是jdbc的DataSource;

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

若是使用mapperCannerConfigurer模式,須要設置掃描根路徑也就是你的mybatis的mapper接口所在包路徑;凡是markerInterface這個接口的子接口都參與到這個掃描,也就是說全部的mapper接口繼承這個SqlMapper。

若是你不使用本身的transaction事務,就使用MapperScannerConfigurer來完成SqlSession的打開、關閉和事務的回滾操做。在此期間,出現數據庫操做的如何異常都會被轉換成DataAccessException,這個異常是一個抽象的類,繼承RuntimeException;

五、 SqlMapper內容以下:

package com.hoo.mapper;
 
   
/**
 * <b>function:</b>全部的Mapper繼承這個接口
 * @author hoojo
 * @createDate 2011-4-12 下午04:00:31
 * @file SqlMapper.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public interface SqlMapper {
 
   
}

六、 實體類和ResultMap.xml

package com.hoo.entity;
 
   
import java.io.Serializable;
import javax.persistence.Entity;
 
   
@Entity
public class Account implements Serializable {
 
   
private static final long serialVersionUID = -7970848646314840509L;
 
   
private Integer accountId;
private Integer status;
private String username;
private String password;
private String salt;
private String email;
private Integer roleId;
 
   
//getter、setter
 
   
@Override
public String toString() {
return this.accountId + "#" + this.status + "#" + this.username + "#" +
this.password + "#" + this.email + "#" + this.salt + "#" + this.roleId;
}
}

account-resultmap.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="accountMap">
<resultMap type="com.hoo.entity.Account" id="accountResultMap">
<id property="accountId" column="account_id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="status" column="status"/>
</resultMap>
</mapper>

七、 在src目錄中添加applicationContext-beans.xml內容以下:

<?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-3.0.xsd"
<!-- 註解探測器 , 在JUnit測試的時候須要-->
<context:component-scan base-package="com.hoo"/>
 
   
</beans>

這裏配置bean對象,一些不能用annotation註解的對象就能夠配置在這裏

八、 在src目錄中添加mybatis.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="com.hoo.entity.Account" alias="account"/>
</typeAliases>
</configuration>

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

九、 AccountMapper接口,內容以下:

package com.hoo.mapper;
 
   
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.hoo.entity.Account;
 
   
/**
 * <b>function:</b>繼承SqlMapper,MyBatis數據操做接口;此接口無需實現類
 * @author hoojo
 * @createDate 2010-12-21 下午05:21:20
 * @file AccountMapper.java
 * @package com.hoo.mapper
 * @project MyBatis
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public interface AccountMapper extends SqlMapper {
 
   
public List<Account> getAllAccount();
 
   
public Account getAccount();
 
   
public Account getAccountById(String id);
 
   
public Account getAccountByNames(String spring);
 
   
@Select("select * from account where username = #{name}")
public Account getAccountByName(String name);
 
   
public void addAccount(Account account);
 
   
public void editAccount(Account account);
 
   
public void removeAccount(int id);
}

這個接口咱們不須要實現,由mybatis幫助咱們實現,咱們經過mapper文件配置sql語句便可完成接口的實現。而後這個接口須要繼承SqlMapper接口,否則在其餘地方就不能從Spring容器中拿到這個mapper接口,也就是說當咱們注入這個接口的時候將會失敗。

固然,你不繼承這個接口也能夠。那就是你須要給買個mapper配置一個bean。配置方法以下:

<bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.hoo.mapper.AccountMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

這裏的MapperFactoryBean能夠幫助咱們完成Session的打開、關閉等操做

十、 在com.hoo.mapper也就是在AccountMapper接口的同一個包下,添加account-mapper.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">
<!-- namespace和定義的Mapper接口對應,並實現其中的方法 -->
<mapper namespace="com.hoo.mapper.AccountMapper">
<!-- id和mapper接口中的方法名對應,resultType使用mybatis.xml中的別名 -->
<select id="getAccount" resultType="account">
<![CDATA[
select * from account limit 1
]]>
</select>
 
   
<select id="getAllAccount" resultType="list" resultMap="accountResultMap">
<![CDATA[
select * from account
]]>
</select>
 
   
<!-- accountResultMap是account-resultmap.xml中定義的resultmap -->
<select id="getAccountById" parameterType="string" resultType="com.hoo.entity.Account" resultMap="accountResultMap">
<![CDATA[
select * from account where account_id = #{id}
]]>
</select>
 
   
<!-- accountMap.accountResultMap是account-resultmap.xml中定義的resultmap,經過namespace.id找到 -->
<select id="getAccountByNames" parameterType="string" resultMap="accountMap.accountResultMap">
<![CDATA[
select * from account where username = #{name}
]]>
</select>
 
   
<sql id="user_name_pwd">
username, password
</sql>
 
   
<!-- 自動生成id策略 -->
<insert id="addAccount" useGeneratedKeys="true" keyProperty="account_id" parameterType="account">
insert into account(account_id, status, username, password)
values(#{accountId}, #{status}, #{username}, #{password})
</insert>
 
   
<!-- 根據selectKey語句生成主鍵 -->
<insert id="addAccount4Key" parameterType="account">
<selectKey keyProperty="account_id" order="BEFORE" resultType="int">
select cast(random() * 10000 as Integer) a from #Tab
</selectKey>
insert into account(account_id, status, username, password)
values(#{accountId}, #{status}, #{username}, #{password})
</insert>
 
   
<update id="editAccount" parameterType="account">
update account set
status = #{status},
username = #{username},
password = #{password}
where account_id = #{accountId}
</update>
 
   
<delete id="removeAccount" parameterType="int">
delete from account where account_id = #{id}
</delete>
</mapper>

上面的namespace和定義接口類路徑對應,全部的sql語句,如select、insert、delete、update的id和方法名稱對應。關於更多MyBatis內容的講解,這裏就不贅述的。這裏只完成整合!若是你不懂能夠去閱讀其餘關於MyBatis的資料。

十一、 爲了測試發佈,這裏使用junit和spring官方提供的spring-test.jar,完成spring框架整合的測試,代碼以下:

package com.hoo.mapper;
 
   
import java.util.List;
import javax.inject.Inject;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
import com.hoo.entity.Account;
 
   
/**
 * <b>function:</b> AccountMapper JUnit測試類
 * @author hoojo
 * @createDate 2011-4-12 下午04:21:50
 * @file AccountMapperTest.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
 
   
@ContextConfiguration("classpath:applicationContext-*.xml")
public class AccountMapperTest extends AbstractJUnit38SpringContextTests {
 
   
@Inject
//@Named("accountMapper")
private AccountMapper mapper;
 
   
public void testGetAccount() {
System.out.println(mapper.getAccount());
}
 
   
public void testGetAccountById() {
System.out.println(mapper.getAccountById("28"));
}
 
   
public void testGetAccountByName() {
System.out.println(mapper.getAccountByName("user"));
}
 
   
public void testGetAccountByNames() {
System.out.println(mapper.getAccountByNames("user"));
}
 
   
public void testAdd() {
Account account = new Account();
account.setEmail("temp@155.com");
account.setPassword("abc");
account.setRoleId(1);
account.setSalt("ss");
account.setStatus(0);
account.setUsername("Jack");
mapper.addAccount(account);
}
 
   
public void testEditAccount() {
Account acc = mapper.getAccountByNames("Jack");
System.out.println(acc);
acc.setUsername("Zhangsan");
acc.setPassword("123123");
mapper.editAccount(acc);
System.out.println(mapper.getAccountById(acc.getAccountId() + ""));
}
 
   
public void testRemoveAccount() {
Account acc = mapper.getAccountByNames("Jack");
mapper.removeAccount(acc.getAccountId());
System.out.println(mapper.getAccountByNames("Jack"));
}
 
   
public void testAccountList() {
List<Account> acc = mapper.getAllAccount();
System.out.println(acc.size());
System.out.println(acc);
}
}

這裏的注入並無使用@Autowired、@Resource、@Qualifier注入,而是使用@Inject、@Named注入方式,Inject注入是JSR330的標準注入方式;而不侷限於某個產品,使用於多個產品的使用,推薦使用這種方式;運行後,沒有發現問題,就能夠繼續後續的編碼工做了。

十二、 定義AccountDao接口及實現代碼,代碼以下:

package com.hoo.dao;
 
   
import java.util.List;
import org.springframework.dao.DataAccessException;
 
   
/**
 * <b>function:</b> Account數據庫操做dao接口
 * @author hoojo
 * @createDate 2011-4-13 上午10:21:38
 * @file AccountDao.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public interface AccountDao<T> {
 
   
/**
 * <b>function:</b> 添加Account對象信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:50:05
 * @param entity Account
 * @return boolean 是否成功
 * @throws DataAccessException
 */
public boolean addAccount(T entity) throws DataAccessException;
 
   
/**
 * <b>function:</b> 根據id對到Account信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:50:45
 * @param id 編號id
 * @return Account
 * @throws DataAccessException
 */
public T getAccount(Integer id) throws DataAccessException;
 
   
/**
 * <b>function:</b> 查詢全部Account信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:51:45
 * @param id 編號id
 * @return Account
 * @throws DataAccessException
 */
public List<T> getList() throws DataAccessException;
}

接口實現

package com.hoo.dao.impl;
 
   
import java.util.List;
import javax.inject.Inject;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import com.hoo.dao.AccountDao;
import com.hoo.entity.Account;
import com.hoo.mapper.AccountMapper;
 
   
/**
 * <b>function:</b> Account數據庫操做dao
 * @author hoojo
 * @createDate 2011-4-13 上午10:25:02
 * @file AccountDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings("unchecked")
@Repository
public class AccountDaoImpl<T extends Account> implements AccountDao<T> {
 
   
@Inject
private AccountMapper mapper;
 
   
public boolean addAccount(T entity) throws DataAccessException {
boolean flag = false;
try {
mapper.addAccount(entity);
flag = true;
} catch (DataAccessException e) {
flag = false;
throw e;
}
return flag;
}
 
   
public T getAccount(Integer id) throws DataAccessException {
T entity = null;
try {
entity = (T) mapper.getAccountById(String.valueOf(id));
} catch (DataAccessException e) {
throw e;
}
return entity;
}
 
   
public List<T> getList() throws DataAccessException {
return (List<T>) mapper.getAllAccount();
}
}

1三、 服務層AccountBiz接口及實現代碼

接口:

package com.hoo.biz;
 
   
import java.util.List;
import org.springframework.dao.DataAccessException;
 
   
/**
 * <b>function:</b> biz層Account接口
 * @author hoojo
 * @createDate 2011-4-13 上午11:33:04
 * @file AccountBiz.java
 * @package com.hoo.biz
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public interface AccountBiz<T> {
/**
 * <b>function:</b> 添加Account對象信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:50:05
 * @param entity Account
 * @return boolean 是否成功
 * @throws DataAccessException
 */
public boolean addAccount(T entity) throws DataAccessException;
 
   
/**
 * <b>function:</b> 根據id對到Account信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:50:45
 * @param id 編號id
 * @return Account
 * @throws DataAccessException
 */
public T getAccount(Integer id) throws DataAccessException;
 
   
/**
 * <b>function:</b> 查詢全部Account信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:51:45
 * @param id 編號id
 * @return Account
 * @throws DataAccessException
 */
public List<T> getList() throws DataAccessException;
}

實現代碼:

package com.hoo.biz.impl;
 
   
import java.util.List;
import javax.inject.Inject;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.hoo.biz.AccountBiz;
import com.hoo.dao.AccountDao;
import com.hoo.entity.Account;
import com.hoo.exception.BizException;
 
   
/**
 * <b>function:</b> Account Biz接口實現
 * @author hoojo
 * @createDate 2011-4-13 上午11:34:39
 * @file AccountBizImpl.java
 * @package com.hoo.biz.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
//@Component
@Service
public class AccountBizImpl<T extends Account> implements AccountBiz<T> {
 
   
@Inject
private AccountDao<T> dao;
 
   
public boolean addAccount(T entity) throws DataAccessException {
if (entity == null) {
throw new BizException(Account.class.getName() + "對象參數信息爲Empty!");
}
return dao.addAccount(entity);
}
 
   
public T getAccount(Integer id) throws DataAccessException {
return dao.getAccount(id);
}
 
   
public List<T> getList() throws DataAccessException {
return dao.getList();
}
}

上面用到了一個自定義的異常信息,代碼以下:

package com.hoo.exception;
 
   
import org.springframework.dao.DataAccessException;
 
   
/**
 * <b>function:</b>自定義Biz層異常信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:42:19
 * @file BizException.java
 * @package com.hoo.exception
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class BizException extends DataAccessException {
 
   
/**
 * @author Hoojo
 */
private static final long serialVersionUID = 1L;
 
   
public BizException(String msg) {
super(msg);
}
 
   
public BizException(String msg, Throwable cause) {
super(msg, cause);
}
}

這裏只是簡單的繼承,若是還有其餘的異常業務或需求能夠進行具體的實現

1四、 springMVC的控制器,AccountController代碼以下:

package com.hoo.controller;
 
   
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hoo.biz.AccountBiz;
import com.hoo.entity.Account;
 
   
/**
 * <b>function:</b> Account控制器
 * @author hoojo
 * @createDate 2011-4-13 上午10:18:02
 * @file AccountController.java
 * @package com.hoo.controller
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@Controller
@RequestMapping("/account")
public class AccountController {
 
   
@Inject
private AccountBiz<Account> biz;
 
   
@RequestMapping("/add")
public String add(Account acc) {
System.out.println(acc);
biz.addAccount(acc);
return "redirect:/account/list.do";
}
 
   
@RequestMapping("/get")
public String get(Integer id, Model model) {
System.out.println("##ID:" + id);
model.addAttribute(biz.getAccount(id));
return "/show.jsp";
}
 
   
@RequestMapping("/list")
public String list(Model model) {
model.addAttribute("list", biz.getList());
return "/list.jsp";
}
 
   
@ExceptionHandler(Exception.class)
public String exception(Exception e, HttpServletRequest request) {
//e.printStackTrace();
request.setAttribute("exception", e);
return "/error.jsp";
}
}

1五、 基本頁面代碼

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% 
 1: 
 2: String path = request.getContextPath();
 3: String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
   
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
 
   
<title>MyBatis 整合  Spring 3.0.5</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
 
   
<body>
<h3>MyBatis 3.0.4  整合  Spring 3.0.5</h3>
<a href="account/list.do">查詢全部</a><br/>
<a href="account/add.do?username=abcdef&password=123132&status=2">添加</a><br/>
<a href="account/get.do?id=25">查詢</a><br/>
</body>
</html>

List.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<% 
 1: 
 2: String path = request.getContextPath();
 3: String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
   
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
 
   
<title>all Account Result</title>
 
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
 
   
<body>
<c:forEach items="${list}" var="data">
id: ${data.accountId }---name: ${data.username }---password: ${data.password }<hr/>
</c:forEach>
</body>
</html>

show.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% 
 1: 
 2: String path = request.getContextPath();
 3: String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
   
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
 
   
<title>show Account</title>
 
   
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
 
   
<body>
${account }<br/>
${account.username }#${account.accountId }
</body>
</html>
 
  

error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Error Page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <H2>Exception: ${exception }</H2> <a href="javascript:document.getElementById('show').style.display = 'block';void(0);"> 詳細信息 </a> <div id="show" style="color: red; display: none;"> <% Exception ex = (Exception)request.getAttribute("exception"); %> <% ex.printStackTrace(new java.io.PrintWriter(out)); %> </div> </body> </html>

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

<!-- 配置事務管理器,注意這裏的dataSource和SqlSessionFactoryBean的dataSource要一致,否則事務就沒有做用了 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

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

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

也許能夠用於jpa、jdo、jta這方面的東西。不知道你們對MyBatis的事務是怎麼處理的?

1七、 對Dao進行擴展封裝,運用SqlSessionDaoSupport進行模板的擴展或運用:

BaseDao代碼以下:

package com.hoo.dao;
 
   
import java.util.List;
 
   
/**
 * <b>function:</b>
 * @author hoojo
 * @createDate 2011-4-12 下午04:18:09
 * @file IBaseDao.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 * @param <T>
 */
public interface BaseDao<T> {
 
   
public boolean add(String classMethod, T entity) throws Exception;
 
   
public boolean edit(String classMethod, T entity) throws Exception;
 
   
public boolean remove(String classMethod, T entity) throws Exception;
 
   
public T get(String classMethod, T entity) throws Exception;
 
   
public List<T> getAll(String classMethod) throws Exception;
}

實現類代碼:

package com.hoo.dao.impl;
 
   
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import com.hoo.dao.BaseDao;
 
   
/**
 * <b>function:</b> 運用SqlSessionDaoSupport封裝Dao經常使用增刪改方法,能夠進行擴展
 * @author hoojo
 * @createDate 2011-4-13 下午06:33:37
 * @file BaseDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@Repository
@SuppressWarnings({ "unchecked", "unused" })
public class BaseDaoImpl<T extends Object> extends SqlSessionDaoSupport implements BaseDao<T> {
 
   
@Inject
private SqlSessionFactory sqlSessionFactory;
 
   
public boolean add(String classMethod, T entity) throws Exception {
boolean flag = false;
try {
flag = this.getSqlSession().insert(classMethod, entity) > 0 ? true : false;
} catch (Exception e) {
flag = false;
throw e;
}
return flag;
}
 
   
public boolean edit(String classMethod, T entity) throws Exception {
boolean flag = false;
try {
flag = this.getSqlSession().update(classMethod, entity) > 0 ? true : false;
} catch (Exception e) {
flag = false;
throw e;
}
return flag;
}
 
   
public T get(String classMethod, T entity) throws Exception {
T result = null;
try {
result = (T) this.getSqlSession().selectOne(classMethod, entity);
} catch (Exception e) {
throw e;
}
return result;
}
 
   
public List<T> getAll(String classMethod) throws Exception {
List<T> result = new ArrayList<T>();
try {
result = this.getSqlSession().selectList(classMethod);
} catch (Exception e) {
throw e;
}
return result;
}
 
   
public boolean remove(String classMethod, T entity) throws Exception {
boolean flag = false;
try {
flag = this.getSqlSession().delete(classMethod, entity) > 0 ? true : false;
} catch (Exception e) {
flag = false;
throw e;
}
return flag;
}
}

值得說明的是,這個類繼承了SqlSessionDaoSupport,它須要咱們幫助它注入SqlSessionFactory或是SqlSessionTemplate,若是二者都被注入將忽略SqlSessionFactory屬性,使用SqlSessionTemplate模板。

繼承SqlSessionDaoSupport後,能夠拿到SqlSession完成數據庫的操做;

1八、 對Dao進行擴展封裝,運用SqlSessionTemplate進行模板的擴展或運用:

首先看看這個組件中運用的一個Mapper的基類接口:

package com.hoo.mapper;
 
   
import java.util.List;
import org.springframework.dao.DataAccessException;
 
   
/**
 * <b>function:</b> BaseSqlMapper繼承SqlMapper,對Mapper進行接口封裝,提供經常使用的增刪改查組件;
 * 也能夠對該接口進行擴展和封裝
 * @author hoojo
 * @createDate 2011-4-14 上午11:36:41
 * @file BaseSqlMapper.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public interface BaseSqlMapper<T> extends SqlMapper {
 
   
public void add(T entity) throws DataAccessException;
 
   
public void edit(T entity) throws DataAccessException;
 
   
public void remvoe(T entity) throws DataAccessException;
 
   
public T get(T entity) throws DataAccessException;
 
   
public List<T> getList(T entity) throws DataAccessException;
}

該接口繼承SqlMapper接口,可是該接口沒有MyBatis的mapper實現。須要咱們本身的業務mapper繼承這個接口,完成上面的方法的實現。

看看繼承SqlSessionTemplate的BaseMapperDao代碼:

package com.hoo.dao;
 
   
import java.util.List;
import com.hoo.mapper.BaseSqlMapper;
 
   
/**
 * <b>function:</b>
 * @author hoojo
 * @createDate 2011-4-14 上午11:30:09
 * @file BaseMapperDao.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public interface BaseMapperDao<T> {
 
   
@SuppressWarnings("unchecked")
public void setMapperClass(Class<? extends BaseSqlMapper> mapperClass);
 
   
public boolean add(T entity) throws Exception;
 
   
public boolean edit(T entity) throws Exception;
 
   
public boolean remove(T entity) throws Exception;
 
   
public T get(T entity) throws Exception;
 
   
public List<T> getAll() throws Exception;
}
package com.hoo.dao.impl;
 
   
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import com.hoo.dao.BaseMapperDao;
import com.hoo.mapper.BaseSqlMapper;
 
   
/**
 * <b>function:</b>運用SqlSessionTemplate封裝Dao經常使用增刪改方法,能夠進行擴展
 * @author hoojo
 * @createDate 2011-4-14 下午12:22:07
 * @file BaseMapperDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
@SuppressWarnings("unchecked")
@Repository
public class BaseMapperDaoImpl<T> extends SqlSessionTemplate implements BaseMapperDao<T> {
 
   
@Inject
public BaseMapperDaoImpl(SqlSessionFactory sqlSessionFactory) {
super(sqlSessionFactory);
}
 
   
private Class<? extends BaseSqlMapper> mapperClass;
 
   
public void setMapperClass(Class<? extends BaseSqlMapper> mapperClass) {
this.mapperClass = mapperClass;
}
 
   
private BaseSqlMapper<T> getMapper() {
return this.getMapper(mapperClass);
}
 
   
public boolean add(T entity) throws Exception {
boolean flag = false;
try {
this.getMapper().add(entity);
flag = true;
} catch (Exception e) {
flag = false;
throw e;
}
return flag;
}
 
   
public boolean edit(T entity) throws Exception {
boolean flag = false;
try {
this.getMapper().edit(entity);
flag = true;
} catch (Exception e) {
flag = false;
throw e;
}
return flag;
}
 
   
public T get(T entity) throws Exception {
return this.getMapper().get(entity);
}
 
   
public List<T> getAll() throws Exception {
return this.getMapper().getList(null);
}
 
   
public boolean remove(T entity) throws Exception {
boolean flag = false;
try {
this.getMapper().remvoe(entity);
flag = true;
} catch (Exception e) {
flag = false;
throw e;
}
return flag;
}
}

上面這個類繼承了SqlSessionTemplate,這個類須要提供一個構造函數。這裏提供的是SqlSessionFactory的構造函數,經過該函數注入SqlSessionFactory便可完成數據庫操做;

例外的是這個類還有一個關鍵屬性mapperClass,這個class須要是BaseSqlMapper接口或是子接口,而後經過SqlSessionTemplate模板得到當前設置的Class的Mapper對象,完成數據庫操做。

該類的測試代碼:

@ContextConfiguration("classpath:applicationContext-*.xml")
public class BaseMapperDaoImplTest extends AbstractJUnit38SpringContextTests {
 
   
@Inject
private BaseMapperDao<Company> dao;
 
   
public void init() {
dao.setMapperClass(CompanyMapper.class);
}
 
   
public void testGet() throws Exception {
init();
Company c = new Company();
c.setCompanyId(4);
System.out.println(dao.get(c));
}
 
   
public void testAdd() throws Exception {
init();
Company c = new Company();
c.setAddress("北京中關村");
c.setName("beijin");
System.out.println(dao.add(c));
}
}

通常狀況下,你能夠在一個Dao中注入BaseMapperDao,緊跟着須要設置MapperClass。只有設置了MapperClass後,BaseMapperDao才能獲取對應mapper,完成相關的數據庫操做。固然你能夠在這個Dao中將SqlSessionTemplate、SqlSession暴露出來,當BaseMapperDao的方法不夠用,能夠進行擴展。

做者:hoojo
出處:

http://www.cnblogs.com/hoojo/archive/2011/04/15/2016324.html
blog: http://blog.csdn.net/IBM_hoojo
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。

版權全部,轉載請註明出處 本文出自:http://www.cnblogs.com/hoojo/archive/2011/04/15/2016324.html
分享道版權全部,歡迎轉載,轉載請註明出處,謝謝
posted on 2011-04-15 10:06 hoojo 閱讀(9975) 評論( 52) 編輯 收藏
1 2

評論:
#3樓 2011-05-09 17:12 | 29163077
SqlSessionTemplate用這個貌似不全哦,我加了mapper子接口測試不經過哦,不知道是哪裏沒有寫全?
#4樓 2011-05-09 17:14 | 29163077
package com.hoo.mapper;

import com.hoo.entity.Account;

public interface AccountSqlMapper extends BaseSqlMapper<Account> {

}

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">
<!--
namespace和定義的Mapper接口對應,並實現其中的方法
,下面的namespace和定義接口類路徑對應,全部的sql語句,如select、insert、delete、update的id和方法名稱對應。
-->
<mapper namespace="com.hoo.mapper.AccountMapper">
<!-- id和mapper接口中的方法名對應,resultType使用mybatis.xml中的別名 -->
<select id="get" resultType="account" parameterType="account">
<![CDATA[
select * from account limit 1
]]>
</select>

<select id="getList" resultType="list" resultMap="accountResultMap">
<![CDATA[
select * from account
]]>
</select>

<!-- accountResultMap是account-resultmap.xml中定義的resultmap -->
<select id="getAccountById" parameterType="string"
resultType="com.hoo.entity.Account" resultMap="accountResultMap">
<![CDATA[
select * from account where account_id = #{id}
]]>
</select>

<!--
accountMap.accountResultMap是account-resultmap.xml中定義的resultmap,經過namespace.id找到
-->
<select id="getAccountByNames" parameterType="string"
resultMap="accountMap.accountResultMap">
<![CDATA[
select * from account where username = #{name}
]]>
</select>

<sql id="user_name_pwd">
username, password
</sql>

<!-- 自動生成id策略 -->
<insert id="add" useGeneratedKeys="true" keyProperty="account_id"
parameterType="account">
insert into account(account_id, status, username,
password)
values(#{accountId}, #{status}, #{username}, #{password})
</insert>

<!-- 根據selectKey語句生成主鍵 -->
<insert id="addAccount4Key" parameterType="account">
<selectKey keyProperty="account_id" order="BEFORE"
resultType="int">
select cast(random() * 10000 as Integer) a from #Tab
</selectKey>
insert into account(account_id, status, username, password)
values(#{accountId}, #{status}, #{username}, #{password})
</insert>

<update id="edit" parameterType="account">
update account set
status
=
#{status},
username = #{username},
password = #{password}
where
account_id = #{accountId}
</update>

<delete id="remove" parameterType="int">
delete from account
where
account_id = #{id}
</delete>
</mapper>

不知道哪裏寫錯了?
#5樓 [ 樓主] 2011-05-10 14:57 | hoojo
@29163077
@29163077
引用29163077:
package com.hoo.mapper;

import com.hoo.entity.Account;

public interface AccountSqlMapper extends BaseSqlMapper<Account> {

}

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">
<!...
AccountSqlMapper 和 <mapper namespace="com.hoo.mapper.AccountMapper">
的namespace沒有對應,要對應。父接口裏面的方法要在mapper.xml中完成實現便可。
#6樓 2011-05-10 16:33 | 29163077
謝謝樓主的答覆,如今我又遇到了一個問題,就是list方法裏的list傳到頁面裏account對象沒有遍歷出來哦,我在後臺打印是成功的,但在頁面上顯示不出,我已經導入了JSTL的2個jar文件。
@RequestMapping("/list")
public String list(Model model) {
List<Account> list = biz.getList();
int size = list.size();
model.addAttribute("accounts", list);
System.out.println("## biz.getList():" + size);
for (int i = 0; i < size; i++) {
System.out
.println("##ID:" + ((Account) list.get(i)).getAccountId());
}
return "/list.jsp";
}
頁面的響應是
id: ${data.accountId}---name: ${data.username}---password: ${data.password}

我嘗試在頁面上也遍歷打印list裏的對象,但報異常,不能轉換爲account對象,
An error occurred at line: 22 in the jsp file: /list.jsp
Generated servlet error:
Account cannot be resolved to a type

我對照其餘springmvc的例子,寫法上應該沒什麼錯誤。不知道爲什麼
#7樓 2011-05-19 17:30 | sunday
樓主寫得很好。能把工程代碼發過來嗎?郵箱:chunming8302@126.com
#8樓 2011-08-25 16:56 | xiaogeng
樓主 ,我按照你的步驟進行,可是junit那步就錯了,異常信息以下,麻煩給看看~~謝謝
011-08-01 16:42:27,265-[MyBatisForSpring] ERROR [main] context.TestContextManager.prepareTestInstance(324) | Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@12f0999] to prepare test instance [testGetAllAccount(com.frame.sample.app.junit.AccountMapperTest)]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.frame.sample.app.junit.AccountMapperTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.frame.sample.app.mapper.AccountMapper com.frame.sample.app.junit.AccountMapperTest.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.frame.sample.app.mapper.AccountMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener
#9樓 2011-09-23 18:21 | skingyang
樓主你好,我在測試spring框架時,出現下面的問題,麻煩看一下:
謝謝!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.ioo.mapper.PersonMapperTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ioo.mapper.PersonMapper com.ioo.mapper.PersonMapperTest.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.ioo.mapper.PersonMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
at org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests.runBare(AbstractJUnit38SpringContextTests.java:205)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:243)
at junit.framework.TestSuite.run(TestSuite.java:238)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
#10樓 [ 樓主] 2011-09-26 11:22 | hoojo
@skingyang
你注入PersonMapper失敗了,看看是你配置了多個PersonMapper仍是注入的時候沒有設置名稱什麼的。
#11樓 2011-09-26 15:07 | skingyang
@hoojo
SqlMapper.java:
public interface SqlMapper {
}

PersonMapper.java:
public interface PersonMapper extends SqlMapper {
public List<Person> searchAll();
}

applicationContext-common.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" http://www.springframework.org/schema/beans"" target="_blank"> http://www.springframework.org/schema/beans"
xmlns:aop=" http://www.springframework.org/schema/aop"" target="_blank"> http://www.springframework.org/schema/aop"
xmlns:tx=" http://www.springframework.org/schema/tx"" target="_blank"> http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

<!-- 配置DataSource數據源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="hello"/>
</bean>

<!-- Spring提供的myBatis的SqlMap配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="configLocation" value="classpath:mybatis.xml"/>
<!-- mapper和resultmap配置路徑 -->
<property name="mapperLocations">
<list>
<!-- 表示在com.ioo.resultmap包或如下全部目錄中,以-resultmap.xml結尾全部文件 -->
<value>classpath:com/ioo/resultmap/**/*-resultmap.xml</value>
<value>classpath:com/ioo/entity/*-resultmap.xml</value>
<value>classpath:com/ioo/mapper/**/*-mapper.xml</value>
</list>
</property>
</bean>

<!-- 經過掃描的模式,掃描目錄在com/ioo/mapper目錄下,全部的mapper都繼承SqlMapper接口的接口, 這樣一個bean就能夠了 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ioo.mapper"/>
<property name="markerInterface" value="com.ioo.mapper.SqlMapper"/>
</bean>
</beans>

person-mapper.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="com.ioo.mapper.PersonMapper">
<!-- 查詢全部記錄 -->
<select
id="searchAll"
resultType="person">
select * from person
</select>
</mapper>

測試類:
@ContextConfiguration("classpath:applicationContext-*.xml")
public class PersonMapperTest extends AbstractJUnit38SpringContextTests {
@Inject
private PersonMapper mapper;

@Test public void testSearchAllTest() { System.out.println(mapper); List<Person> ls = mapper.searchAll(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < ls.size(); i++) { Person person = ls.get(i); sb.append(person.getId()); sb.append("\t"); sb.append(person.getName()); sb.append("\t"); sb.append(person.getSex()); sb.append("\t"); sb.append(person.getBirthday()); sb.append("\n"); } System.out.println(sb.toString()); } }
相關文章
相關標籤/搜索