广告
返回顶部
首页 > 资讯 > 后端开发 > Python >MyBatis3+SpringMVC3
  • 890
分享到

MyBatis3+SpringMVC3

2023-01-31 01:01:08 890人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

首先说明: 文章是转的。 源码地址:Http://download.csdn.net/detail/yjflinchong/4206045 开发环境: System:windows WEBBrowser:IE6+、Fi


首先说明: 文章是转的。


源码地址:Http://download.csdn.net/detail/yjflinchong/4206045


开发环境:

System:windows

WEBBrowser:IE6+、Firefox3+

JavaEE Server:Tomcat5.0.2.8、tomcat6

IDE:eclipse、MyEclipse 8

Database:Mysql

开发依赖库:

JavaEE5、spring 3.0.5、mybatis 3.0.4、myBatis-spring-1.0、junit4.8.2

1、 首先新建一个WebProject 命名为MyBatisForSpring,新建项目时,使用JavaEE5的lib库。然后手动添加需要的jar包,所需jar包如下:

clip_image002

2、 添加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>*-resultmap.xml</value>
                <value>classpath:com/hoo/entity*-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;

5、 SqlMapper内容如下:

package com.hoo.mapper;
 
public interface SqlMapper {
 
}

6、 实体类和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>

7、 在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注解的对象就可以配置在这里

8、 在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,这里就不需要配置)等

9、 AccountMapper接口,内容如下:

package com.hoo.mapper;
 
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.hoo.entity.Account;
 
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的打开、关闭等操作

10、 在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的资料。

11、 为了测试发布,这里使用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;
 
 
@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的标准注入方式;而不局限于某个产品,使用于多个产品的使用,推荐使用这种方式;运行后,没有发现问题,就可以继续后续的编码工作了。

12、 定义AccountDao接口及实现代码,代码如下:

package com.hoo.dao;
 
import java.util.List;
import org.springframework.dao.DataAccessException;
 
public interface AccountDao<T> {
    
    
    public boolean addAccount(T entity) throws DataAccessException;
    
    
    public T getAccount(Integer id) 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;
 
@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();
    }
}

13、 服务层AccountBiz接口及实现代码

接口:

package com.hoo.biz;
 
import java.util.List;
import org.springframework.dao.DataAccessException;
 
public interface AccountBiz<T> {
    
    public boolean addAccount(T entity) throws DataAccessException;
    
    
    public T getAccount(Integer id) 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;
 
//@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;
 
public class BizException extends DataAccessException {
 
    
    private static final long serialVersionUID = 1L;
    
    public BizException(String msg) {
        super(msg);
    }
 
    public BizException(String msg, Throwable cause) {
        super(msg, cause);
    }
}

这里只是简单的继承,如果还有其他的异常业务或需求可以进行具体的实现

14、 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;
 
@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";
    }
}

15、 基本页面代码

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>

16、 以上就基本上完成了整个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的事务是怎么处理的?

17、 对Dao进行扩展封装,运用SqlSessionDaoSupport进行模板的扩展或运用:

BaseDao代码如下:

package com.hoo.dao;
 
import java.util.List;
 
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;
 
@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完成数据库的操作;

18、 对Dao进行扩展封装,运用SqlSessionTemplate进行模板的扩展或运用:

首先看看这个组件中运用的一个Mapper的基类接口:

package com.hoo.mapper;
 
import java.util.List;
import org.springframework.dao.DataAccessException;
 
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;
 
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;
 
@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的方法不够用,可以进行扩展。


--结束END--

本文标题: MyBatis3+SpringMVC3

本文链接: https://www.lsjlt.com/news/183834.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • MyBatis3+SpringMVC3
    首先说明: 文章是转的。 源码地址:http://download.csdn.net/detail/yjflinchong/4206045 开发环境: System:Windows WebBrowser:IE6+、Fi...
    99+
    2023-01-31
  • springmvc3个适配器
    SimpleControllerHandlerAdapterpublic class SimpleControllerHandlerAdapter implements HandlerAdapter { @Override ...
    99+
    2023-01-31
    适配器
  • mybatis3中@SelectProv
    mybatis的原身是ibatis,现在已经脱离了apache基金会,新官网是http://www.mybatis.org/。mybatis3中增加了使用注解来配置Mapper的新特性,本篇文章主要介绍其中几个@Provider的使用方式,...
    99+
    2023-01-31
    SelectProv
  • java mybatis3 forea
    最近在用mybatis3做项目,需要很多的批量操作,所以就写了一些Demo,同时分享给大家,希望对您有用。首先说一下foreach标签中几个重要的属性的含义:字段名含义item指集合里面的数据项对象,如果是List,则表示list中所代表的...
    99+
    2023-01-31
    java forea
  • Mybatis3+Spring4+SpringMVC4 整合【转】
     首先在整合这个框架的时候,想想其一般的步骤是怎样的,先有个步骤之后,不至于在后面的搞混了,这样在整合的时候也比较清晰些。然后我们就细细的一步一步来整合。1  创建一个Web项目。&nb...
    99+
    2022-10-18
  • 对Mybatis3源码结构理解
    一、mybatis简介    Mybatis是支持普通SQL查询查询、存储过程和高级映射的优秀持久层框架。Mybatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。Mybatis使用简单的XML或注解用于配置和原始映射,将...
    99+
    2023-01-31
    源码 结构
  • 如何部署并运行MyBatis3
    这篇文章主要介绍“如何部署并运行MyBatis3”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何部署并运行MyBatis3”文章能帮助大家解决问题。源码部署下载mybatis3中文网址:mybat...
    99+
    2023-07-02
  • Mybatis3详解(六)——动态SQL
    原文:https://www.cnblogs.com/tanghaorong/p/13960269.html...
    99+
    2018-12-01
    Mybatis3详解(六)——动态SQL 数据库入门 数据库基础教程
  • mybatis3中@SelectProvider传递参数方式
    mybatis3 @SelectProvider传递参数 一、通常情况下我喜欢使用实体或者vo去传参数 这样在Provide的方法中可以直接通过#{param}(param...
    99+
    2022-11-12
  • MyBatis3一个查询DAO的实现
    MyBatis3一个查询DAO的实现 public List<Ord> queryOrd(String ordno, String custno, int startRow, int rowSize, Ord.St.....
    99+
    2023-01-31
    DAO
  • MyBatis3.X复杂Sql查询的语句
    目录MyBatis3.X复杂Sql查询MyBatis3.X的resultMapResultMap复杂对象一对一查询结果映射之associationResultMap复杂对象一对多查询...
    99+
    2022-11-12
  • 关于mybatis3中@SelectProvider的使用问题
    mybatis3中增加了使用注解来配置Mapper的新特性,本篇文章主要介绍其中几个@Provider的使用方式,他们是:@SelectProvider、@UpdatePr...
    99+
    2022-11-12
  • SSM框架之MyBatis3专题3:关联
    当查询内容涉及具有关联关系的多个表时,就需要使用关联关系查询。根据表与表之间的关联关系的不同,关联查询分为四种:1、一对一关联查询;2、一对多关联查询;3、多对一关联查询;4、多对多关联查询; 由于日常工作中最常见的关联关系是一对多、多...
    99+
    2023-01-31
    框架 专题 SSM
  • MyBatis3 DynamicSql风格语法使用方法
    这篇文章主要介绍“MyBatis3 DynamicSql风格语法使用方法”,在日常操作中,相信很多人在MyBatis3 DynamicSql风格语法使用方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”MyB...
    99+
    2023-06-07
  • SpringMvc3+extjs4实现上传与下载功能的代码解析
    这篇文章主要讲解了SpringMvc3+extjs4实现上传与下载功能的代码解析,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。本文实例为大家分享了SpringMvc3+extjs4实现上传与下载的具体代码,供大...
    99+
    2023-05-31
    springmvc3 extjs4
  • 关于mybatis3中几个@Provider的使用方式
    目录一、@SelectProvider二、@InsertProvider三、@UpdateProvider四、@DeleteProviderMybatis的原身是ibati...
    99+
    2022-11-13
  • mybatis3中@SelectProvider传递参数方式是什么
    这篇文章主要讲解了“mybatis3中@SelectProvider传递参数方式是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“mybatis3中@SelectProvider...
    99+
    2023-06-20
  • mybatis3中@SelectProvider的使用问题怎么解决
    今天就跟大家聊聊有关mybatis3中@SelectProvider的使用问题怎么解决,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。mybatis3中增加了使用注解来配置M...
    99+
    2023-06-22
  • MyBatis3源码解析之怎么获取数据源
    这篇文章主要讲解了“MyBatis3源码解析之怎么获取数据源”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“MyBatis3源码解析之怎么获取数据源”吧!jdbc再贴一个JDBC运行的测试方法...
    99+
    2023-07-02
  • MyBatis3源码解析之如何获取数据源详解
    目录前言jdbc传统JDBC弊端思考源码分析获取数据源总结前言 上文讲的MyBatis部署运行且根据官网运行了一个demo:一步到位部署运行MyBatis3源码<保姆级>...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作