Mybatis 与 spring mvc

本文是用来小结一下自己mybatis 和spring mvc 学习过程。 在写的过程中发现 http://www.phperz.com/article/15/0127/48684.html 这篇文章里面的Mybatis应用学习讲的不错,所以记录一下网址,如果自己写的太烂可以看这个。

在写的过程中发现http://www.cnblogs.com/rollenholt/p/3365866.html 写的也很好,看过很多这个博主的文章了,和他年纪差不多,真是难以望其项背啊...

1.使用spring mvc 与 Mybatis 组合的架构   首先需要导入相应的jar包

2.配置文件方面

spring mvc 需要   applicationContext.xml      xxxx-servlet.xml    

Mybatis  需要在applicationContext.xml 中的一些配置   以及对应的xxxxMapper.xml

一个简单的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" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
    
    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="novel.hr.user.Dao"/>
    <context:component-scan base-package="novel.hr.user.service"/>
    <context:component-scan base-package="novel.hr.user.control"/>

    <!--扫描配置文件,读取配置文件中的信息  例如 ${jdbc.url}   -->
    <context:property-placeholder location="/WEB-INF/classes/config/jdbcConfig.properties"/>
   
    <!--数据源,配置的比较简单 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
       destroy-method="close">  
       <property name="driverClassName" value="${jdbc.driver}" />  
       <property name="url" value="${jdbc.url}" />  
       <property name="username" value="${jdbc.username}" />  
       <property name="password" value="${jdbc.password}" />  
    </bean>  
   
   <!--Mybatis的SessionFactory   在其中指定了数据源以及Mapper,xml配置文件的位置-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource" />
              <property name="mapperLocations"
                     value="/WEB-INF/classes/config/mybatismapper/*Mapper.xml" /> 
    </bean>
     
     <!--MapperScanner,通过配置Scanner 和需要扫描的包,就可以将包中定义的mapper接口类注入到需要使用的地方,而不必手动实例化-->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="novel.hr.user.Dao" />
    </bean>
    
      
 <!--     ====事务相关控制===== 为事务管理器添加所要管理的数据源  --> 
  <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">     
          <property name="dataSource" ref="dataSource"></property>
    </bean>     
  
  <!--  advice 指定哪些方法需要事务管理  以及相应的配置--> 
  <tx:advice id="userTxAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="delete*" propagation="REQUIRED" read-only="false" 
                            rollback-for="java.lang.Exception" no-rollback-for="java.lang.RuntimeException"/>
      <tx:method name="insert*" propagation="REQUIRED" read-only="false" 
                            rollback-for="java.lang.RuntimeException" />
      <tx:method name="update*" propagation="REQUIRED" read-only="false" 
                            rollback-for="java.lang.Exception" />
      
      <tx:method name="find*" propagation="SUPPORTS"/>
      <tx:method name="get*" propagation="SUPPORTS"/>
      <tx:method name="select*" propagation="SUPPORTS"/>
    </tx:attributes>
  </tx:advice>
 
  <!-- 定义aop的切入点   切入点按照expression来定义--> 
  <aop:config>    
    <aop:pointcut id="pc" expression="execution( * novelhr.user.service.*.*(..))" />
    <aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
  </aop:config>
      
    <!--视图管理器    使spring mvc 返回string后自动加  前后缀,然后返回最终的视图  -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:viewClass="org.springframework.web.servlet.view.JstlView" 
        p:prefix="/WEB-INF/view/"
        p:suffix=".jsp" 
    />
</beans>

配置了applicationContext之后,还需要配置xxx-servlet.xml  这个文件中的内容可以覆盖掉application中的配置。由于需要配置的基本在applicationContext中配置过了,所以这个的具体内容略过。

接下来的mapper的配置

<?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="novel.hr.user.Dao.UserManageMapper">
    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复
    使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型
    resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回
    User类就是users表所对应的实体类
    -->
    <!-- 
        根据id查询得到一个user对象
     -->
     
    <select id="getUserCheck" parameterType="novel.hr.user.domain.Employee"
        resultType="novel.hr.user.domain.Employee">
        select * from Employee where EmployeeNum=#{employeeNum} and password=#{password}
    </select>
    
  <!--  <update id="updateUser" parameterType="User" >
        update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
    </update>
     --> 
    <!--seGeneratedKeys设置为"true"表明要MyBatis获取由数据库自动生成的主键;
        keyProperty="id"指定把获取到的主键值注入到Student的id属性--> 
  <!--   <insert id="addUser" parameterType="User" 
        useGeneratedKeys="true" keyProperty="id"> 
     insert into user(userName,userAge,userAddress) values(#{userName},#{userAge},#{userAddress}) 
     </insert> 
     
     <delete id="deleteUser" parameterType="int">
        delete from user where id=#{id}
    </delete>

-->


<!-- User 联合文章进行查询 方法之一的配置 (多对一的方式)  
    <resultMap id="resultUserArticleList" type="Article">
        <id property="id" column="aid" />
        <result property="title" column="title" />
        <result property="content" column="content" />
        
        <association property="user" javaType="User">
            <id property="id" column="id" />
            <result property="userName" column="userName" />
            <result property="userAddress" column="userAddress" />            
        </association>        
    </resultMap>

<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
       select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article 
              where user.id=article.userid and user.id=#{id}
    </select>-->
    
    
    
    <!--   article 类中有一个user类的实例。也就是表的外键关系。有这个也可以看出一对一与一对多的方法,换成List就好 
  
    
    <resultMap id="resultUserArticleList" type="Article">
        <id property="id" column="aid" />
        <result property="title" column="title" />
        <result property="content" column="content" />
        
        <association property="user" javaType="User">
            <id property="id" column="id" />
            <result property="userName" column="userName" />
            <result property="userAddress" column="userAddress" />            
        </association>        
    </resultMap>

<select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
       select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article 
              where user.id=article.userid and user.id=#{id}
    </select>
     -->
     
     <!--    一对多的 
     <resultMap type="User" id="resultListUser">
        <id column="id" property="id" />
        <result column="userName" property="userName" />
        <result column="userAge" property="userAge" />
        <result column="userAddress" property="userAddress" />
    </resultMap>

  
    <resultMap id="resultUserArticleList-2" type="Article">
        <id property="id" column="aid" />
        <result property="title" column="title" />
        <result property="content" column="content" />        
        <association property="user" javaType="User" resultMap="resultListUser" />             
    </resultMap>
    
    <select id="getUserArticles" parameterType="int" resultMap="resultUserArticleList">
       select user.id,user.userName,user.userAddress,article.id aid,article.title,article.content from user,article 
              where user.id=article.userid and user.id=#{id}
    </select>
     -->
     
</mapper>

动态SQL的没用到,但是觉得肯定会有用,所以直接粘贴过来

mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句
mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:
1. if 语句 (简单的条件判断)
2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.
3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)
5. set (主要用于更新时)
6. foreach (在实现 mybatis in 语句查询时特别有用)
下面分别介绍这几种处理方式

1. mybaits if 语句处理

<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="content != null">
            and content = #{content}
        </if>
        <if test="owner != null">
            and owner = #{owner}
        </if>
    </select>

这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候, 它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了

2.2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似 

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 1 
        <choose>
            <when test="title != null">
                and title = #{title}
            </when>
            <when test="content != null">
                and content = #{content}
            </when>
            <otherwise>
                and owner = "owner1"
            </otherwise>
        </choose>
    </select>
when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时 候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的 内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。

3.trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀) 

 <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
        select * from t_blog 
        <trim prefix="where" prefixOverrides="and |or">
            <if test="title != null">
                title = #{title}
            </if>
            <if test="content != null">
                and content = #{content}
            </if>
            <if test="owner != null">
                or owner = #{owner}
            </if>
        </trim>
    </select>

trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容 的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为 trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能

4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or 条件

<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
        select * from t_blog 
        <where>
            <if test="title != null">
                title = #{title}
            </if>
            <if test="content != null">
                and content = #{content}
            </if>
            <if test="owner != null">
                and owner = #{owner}
            </if>
        </where>
    </select>
where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子 的,MyBatis会智能的帮你处理,如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;此外,在where元素中你不需要考虑空格的问 题,MyBatis会智能的帮你加上。像上述例子中,如果title=null, 而content != null,那么输出的整个语句会是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或 or 给忽略。

5.set (主要用于更新时) 

<update id="dynamicSetTest" parameterType="Blog">
        update t_blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>
            <if test="content != null">
                content = #{content},
            </if>
            <if test="owner != null">
                owner = #{owner}
            </if>
        </set>
        where id = #{id}
    </update>

set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段

6. foreach (在实现 mybatis in 语句查询时特别有用) 
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面 也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的 map里面的key

1.1.单参数List的类型

<select id="dynamicForeachTest" resultType="Blog">
        select * from t_blog where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

上述collection的值为list,对应的Mapper是这样的


public List<Blog> dynamicForeachTest(List<Integer> ids);  
测试代码

 @Test
    public void dynamicForeachTest() {
        SqlSession session = Util.getSqlSessionFactory().openSession();
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(3);
        ids.add(6);
        List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
        for (Blog blog : blogs)
            System.out.println(blog);
        session.close();
    }

2.数组类型的参数

    <select id="dynamicForeach2Test" resultType="Blog">
        select * from t_blog where id in
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>
对应mapper

public List<Blog> dynamicForeach2Test(int[] ids);  

3. Map 类型的参数

    <select id="dynamicForeach3Test" resultType="Blog">
        select * from t_blog where title like "%"#{title}"%" and id in
        <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

mapper 应该是这样的接口:

public List<Blog> dynamicForeach3Test(Map<String, Object> params); 
通过以上方法,就能完成一般的mybatis 的 动态SQL 语句.最常用的就是  if where foreach这几个,一定要重点掌握.
 

到此配置文件结束。在使用的时候代码如下

Dao接口

package novel.hr.user.Dao;


public interface UserManagerDao {

    Object getUserCheck(int EmployeeNum , String password);
}

Mapper接口

package novel.hr.user.Dao;


import novel.hr.user.domain.Employee;

public interface UserManageMapper {

    Employee getUserCheck(Employee param);
}

dao实现类

@Repository
public class UserManageDaoImpl implements UserManagerDao{

    @Autowired
    private UserManageMapper umm;
    
    @Override
    public Employee getUserCheck(int EmployeeNum , String password){
        
        Employee param=new Employee();
        param.setEmployeeNum(EmployeeNum);
        param.setPassWord(password);
        return umm.getUserCheck(param);
    }
    
}

简单一点的可以直接用service层调用mapper接口,省略dao,因为mapper其实已经起到了dao的作用。

相对于学习Hibernate的过程,我觉得Mybatis更加简单易用一些。

如果有新的再加

原文地址:https://www.cnblogs.com/mamuluke/p/5157865.html