7.2 Mybatis

7.2 Mybatis

平时我们都用JDBC访问数据库,除了需要自己写SQL之外,还必须操作Connection, Statement, ResultSet 这些其实只是手段的辅助类。 不仅如此,访问不同的表,还会写很多雷同的代码,显得繁琐和枯燥。
那么用了Mybatis之后,只需要自己提供SQL语句,其他的工作,诸如建立连接,Statement, JDBC相关异常处理等等都交给Mybatis去做了,那些重复性的工作Mybatis也给做掉了,我们只需要关注在增删改查等操作层面上,而把技术细节都封装在了我们看不见的地方。

在src目录下创建mybatis的主配置文件mybatis-config.xml (相当于hibernate.cfg.xml)

1. 应用程序找Mybatis要数据

public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=sqlSessionFactory.openSession();
         
        List<Category> cs=session.selectList("listCategory");
        for (Category c : cs) {
            System.out.println(c.getName());
        }

2. mybatis从数据库中找来数据

2.1 通过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.how2java.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
    </mappers>
</configuration>

2.2 通过Category.xml执行对应的select语句

<?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.how2java.pojo">
        <select id="listCategory" resultType="Category">
            select * from   category_     
        </select>
    </mapper>

2.3 基于Category.xml把返回的数据库记录封装在Category对象中

2.4 把多个Category对象装在一个Category集合中

2.5 返回一个Category集合

3.mappper里的增删改查。

其中mappper中的标签对应Dao层的调用方法。在运行项目中,如果id对用不上。或者重复,会报注入bean错误

parameterType表示需要注入的实体或者类型
resultType表示为查询或者调用SQL返回的实体类型
<?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.how2java.pojo">
        <insert id="addCategory" parameterType="Category" >
            insert into category_ ( name ) values (#{name})   
        </insert>
         
        <delete id="deleteCategory" parameterType="Category" >
            delete from category_ where id= #{id}  
        </delete>
         
        <select id="getCategory" parameterType="_int" resultType="Category">
            select * from   category_  where id= #{id}   
        </select>
 
        <update id="updateCategory" parameterType="Category" >
            update category_ set name=#{name} where id=#{id}   
        </update>
        <select id="listCategory" resultType="Category">
            select * from   category_     
        </select>    
    </mapper>

3.1模糊查询

mysql:select * from category_ where name like concat('%',#{0},'%')

oracle:select * from category_ where name like '%'||#{0}||'%'

3.2多条件查询

在dao层多个@parm参数,然后根据入参map多个条件查询

<select id="listCategoryByIdAndName"  parameterType="map" resultType="Category">
            select * from   category_  where id> #{id}  and name like concat('%',#{name},'%')
        </select>   
3.3表间关系为一对一,一对多,多对多的注入
四、动态SQL
4.1if 通常为输入条件时使用
 
<select id="listProduct" resultType="Product">
    select * from product_
    <if test="name!=null">
        where name like concat('%',#{name},'%')
    </if>             
</select>

4.2 where 标签

通常有多个条件时使用

 <select id="listProduct" resultType="Product">
        select * from product_
        <where>
            <if test="name!=null">
                and name like concat('%',#{name},'%')
            </if>        
            <if test="price!=null and price!=0">
                and price > #{price}
            </if>
        </where>     
    </select>

4.3 set标签;与where标签类似的,在update语句里也会碰到多个字段相关的问题。 在这种情况下,就可以使用set标签:

 <update id="updateProduct" parameterType="Product" >
        update product_
        <set>
            <if test="name != null">name=#{name},</if>
            <if test="price != null">price=#{price}</if>
              
        </set>
         
         where id=#{id}   
    </update>

4.4trim 用来定制想要的功能,比如where标签就可以用,来替换
运行set标签中的代码,其效果是一样的。

    <select id="listProduct" resultType="Product">
        select * from product_
        <trim prefix="WHERE" prefixOverrides="AND |OR ">
            <if test="name!=null">
                and name like concat('%',#{name},'%')
            </if>        
            <if test="price!=null and price!=0">
                and price > #{price}
            </if>
        </trim>      
    </select>
     
    <update id="updateProduct" parameterType="Product" >
        update product_
        <trim prefix="SET" suffixOverrides=",">
            <if test="name != null">name=#{name},</if>
            <if test="price != null">price=#{price}</if>
              
        </trim>
         
         where id=#{id}   
    </update>

4.5 Mybatis里面没有else标签,但是可以使用when otherwise标签来达到这样的效果。

<select id="listProduct" resultType="Product">
      SELECT * FROM product_ 
      <where>
          <choose>
          <when test="name != null">
            and name like concat('%',#{name},'%')
          </when>              
          <when test="price !=null and price != 0">
            and price > #{price}
          </when>                      
            <otherwise>
                and id >1
            </otherwise>
          </choose>
      </where>
</select>

4.6 foreach标签,相当于运行的查询条件是一个集合,用in条件。

<select id="listProduct" resultType="Product">
          SELECT * FROM product_
            WHERE ID in
                <foreach item="item" index="index" collection="list"
                    open="(" separator="," close=")">
                    #{item}
                </foreach>
    </select>

4.7 bind标签,bind标签就像是再做一次字符串拼接,方便后续使用

        <!-- 本来的模糊查询方式 -->
<!--         <select id="listProduct" resultType="Product"> -->
<!--             select * from   product_  where name like concat('%',#{0},'%') -->
<!--         </select> -->
             
        <select id="listProduct" resultType="Product">
            <bind name="likename" value="'%' + name + '%'" />
            select * from   product_  where name like #{likename}
        </select>
 
原文地址:https://www.cnblogs.com/Smileing/p/11487871.html