首页 > 编程语言 > 详细

MyBatis学习(三)---MyBatis和Spring整合

时间:2018-01-21 21:15:31      阅读:242      评论:0      收藏:0      [点我收藏+]

想要了解MyBatis基础的朋友可以通过传送门:

  MyBatis学习(一)---配置文件,Mapper接口和动态SQL  http://www.cnblogs.com/ghq120/p/8322302.html

  MyBatis学习(二)---数据表之间关联  http://www.cnblogs.com/ghq120/p/8323918.html

  之前两篇文章都是单独介绍了MyBatis的用法,并没有和任何框架进行整合。使用MyBatis完成数据库的操作仍有一些模板化的代码,比如关闭SqlSession、提交事务等。

  MyBatis和Spring整合只有dao组件的接口没有实现类,避免了显式调用SqlSession的相关操作数据库的方法,事务的提交和SqlSession的关闭。

  实现MyBatis和Spring整合且只有接口没有实现类的要求是:dao组件接口的主文件名和映射文件的主文件名同名,且在同包下,映射文件的命名空间必须是dao组件接口的全限定名,标志相应的sql语句的id必须是接口的方法名。

 

MyBatis+Spring

此项目实现的还是用户的增删改查

技术分享图片

使用Spring后,就不需要使用工具类来获取SqlSessionFactory和SqlSession的对象。通过在Spring容器中配置bean元素来自动获取。

Spring容器的配置文件如下applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=
    "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!-- 配置数据源,指出连接数据库需要的驱动、url、用户名和密码以及连接池相关信息 -->
    <bean id="dbcpdataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
        <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property>
        <property name="username" value="scott"></property>
        <property name="password" value="itcast"></property>
        <property name="initialSize" value="20"></property>
        <property name="maxActive" value="10"></property>
        <property name="maxIdle" value="3"></property>
        <property name="minIdle" value="2"></property>
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="mybatis-config.xml"></property>
        <property name="dataSource" ref="dbcpdataSource"></property>
    </bean>
    
    <!-- 配置Dao组件接口的代理类,该bean元素只能配置一个Dao组件的代理类,如果要配置多个,该bean元素要出现多次,根据id来区分 -->
    <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
      <property name="mapperInterface" value="com.ghq.model.dao.UserDao"></property>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
</beans>

 

 

由于Spring容器中已经和数据库建立连接,则MyBatis配置文件中无需再次建立和数据库的连接,mybatis-config.xml的配置如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  
<configuration>    
    <!-- 在配置文件中定义别名,可以在映射文件中使用别名 -->
    <typeAliases>
        <package name="com.ghq.model.entity"/>
    </typeAliases>
    
  <!-- 注册映射文件 -->
  <mappers>
    <package name="com.ghq.model.dao"/>
  </mappers>
</configuration>

 

dao组件中的方法为

public interface UserDao {
    //根据模糊姓名和性别查询
    List<User> getUserBynameAndGender(Map<String,Object> m);
    //批量删除用户
    public boolean delBatchUser(UserVo vo);
}

 

dao组件的配置文件UserDao.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.ghq.model.dao.UserDao">
    <select id="getUserBynameAndGender" parameterType="java.util.Map" resultType="user">
    select * from user_tab 
    <!-- where 标签默认会去除第一个and,若输入参数是null,则删除where条件 -->
    <where>
        <if test="username != null and username != ‘‘">
            and username like ‘%${username}%‘
        </if>
        <if test="gender !=null and gender !=‘‘">
            and gender = #{gender}
        </if>
    </where>
  </select>

    <delete id="delBatchUser" parameterType="UserVo">
    delete from user_tab 
    <where>
      <if test="idlist !=null and idlist.size() > 0">
        and id in
        <foreach collection="idlist" item="id" open="(" close=")" separator=",">
          #{id}
        </foreach>
      </if>
    </where>
  </delete>

</mapper>

 

 

单元测试

使用Spring容器来创建对象,则需要先加载Spring容器,创建dao组件接口的对象,调用对象中的方法。

public class testmybatis {
    //根据条件来获取用户
    @Test
    public void testgetUserbynameAndGender(){
        SqlSession session = MybatisDb.getSession();
        UserDao userdao = session.getMapper(UserDao.class);
        Map<String,Object> user = new HashMap<String,Object>();
        user.put("username", "张");
        user.put("gender", "女");
        List<User> ulist = userdao.getUserBynameAndGender(user);
        if (ulist !=null && ulist.size() > 0) {
            for (User uu : ulist) {
                System.out.println(uu);
            }
        } else {
            System.out.println("没有符合条件的用户");
        }        
    }

    //批量删除用户的方法
    @Test
    public void testdelBatchUser(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserDao userDao = (UserDao)context.getBean("userDao");
        UserVo vo = new UserVo();
        List<Integer> idlist = new ArrayList<Integer>();
        idlist.add(8);
        idlist.add(6);
        vo.setIdlist(idlist);
        boolean flag = userDao.delBatchUser(vo);
        if (flag) {
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
    }

 

MyBatis学习(三)---MyBatis和Spring整合

原文:https://www.cnblogs.com/ghq120/p/8325463.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!