Mybatis 配置的xml文件: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>

<!-- 别名,自动扫描com.how2java.pojo下的类型,使得在后续配置文件Category.xml中使用resultType的时候,
可以直接使用Category,而不必写全com.how2java.pojo.Category -->
    <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="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射Category.xml -->
    <mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
    </mappers>
    
</configuration>

增删改查

<!--resultType="Category" 表示返回的数据和Category关联起来-->
 <mapper namespace="com.how2java.pojo">
         <select id="listCategory" resultType="Category"> 
             select * from category_   
         </select> 
         
        <delete id="deleteCategory" parameterType="Category">
        	delete from category_ where id= #{id}
        </delete>
       
        <insert id="addCategory" parameterType="Category">
        	insert into category_(name)
        	values(#{name})        	
        </insert>
  
        <update id="updateCategory" parameterType="Category">
        update category_ set name=#{name} where id= #{id}
        </update>
        </mapper>

模糊查询:

<!-- 模糊查询 -->
       	<select id="listCategoryByName" parameterType="string" resultType="Category">
       	select * from category_  where name like concat('%',#{name},'%')
       	</select>
        
        <!-- 多条件模糊查询 -->
        <select id="listCategoryByIdAndName" parameterType="map" resultType="Category">
        select * from category_ where id>#{id} and name like concat('%',#{name},'%')
        </select>

一对多关系:

对应的实体:Category:

package com.how2java.pojo;
 
import java.util.List;
 
public class Category {
    private int id;
    private String name;
    List<Product> products;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Product> getProducts() {
        return products;
    }
    public void setProducts(List<Product> products) {
        this.products = products;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
     
}

Product:

package com.how2java.pojo;
 
public class Product {
    private int id;
    private String name;
    private float price;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
    }
 
}
<resultMap type="Category" id="categoryBean">
            <id column="cid" property="id" />
            <result column="cname" property="name" />     
            <!-- 一对多的关系 -->
            <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 products Category类里的products -->
            <collection property="products" ofType="Product">
                <id column="pid" property="id" />
                <result column="pname" property="name" />
                <result column="price" property="price" />
            </collection>
        </resultMap>
        
         <!-- 关联查询分类和产品表 -->
        <select id="listCategory" resultMap="categoryBean">
             select c.*, p.*, c.id cid, p.id pid, c.name cname, p.name pname from category_ c left join product_ p on c.id = p.cid
        </select>
<id/>表示主键

输出语句:

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);
            List<Product> ps = c.getProducts();
            for (Product p : ps) {
                System.out.println("\t"+p);
            }
        }

preparestatement输出执行的SQL_mysql


preparestatement输出执行的SQL_mysql_02


多对一关系:

实体:Product:

package com.how2java.pojo;
 
public class Product {
    private int id;
    private String name;
    private float price;
    private Category category;
     
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
    }
 
}

Category:

package com.how2java.pojo;
 
import java.util.List;
 
public class Category {
    private int id;
    private String name;
    List<Product> products;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Product> getProducts() {
        return products;
    }
    public void setProducts(List<Product> products) {
        this.products = products;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
     
}

mybatis-config.xml下的mappers对要增加对Product.xml的映射:

<mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
        <mapper resource="com/how2java/pojo/Product.xml"/>
    </mappers>

Product.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.how2java.pojo">
        <resultMap type="Product" id="productBean">
            <id column="pid" property="id" />
            <result column="pname" property="name" />
            <result column="price" property="price" />
     
            <!-- 多对一的关系 -->
            <!-- property: 指的是属性名称, javaType:指的是属性的类型 -->
            <!-- 使用association 进行多对一关系关联,指定表字段名称与对象属性名称的一一对应关系 -->
            <association property="category" javaType="Category">
                <id column="cid" property="id"/>
                <result column="cname" property="name"/>
            </association>
        </resultMap>
     
        <!-- 根据id查询Product, 关联将Orders查询出来 -->
        <select id="listProduct" resultMap="productBean">
            select c.*, p.*, c.id 'cid', p.id 'pid', c.name 'cname', p.name 'pname' from category_ c left join product_ p on c.id = p.cid
        </select>   
    </mapper>

输出语句:

String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=sqlSessionFactory.openSession();
      //多对一关系:
        List<Product> ps = session.selectList("listProduct");
        for(Product s:ps) {
        	System.out.println(s+"  属  于  "+s.getCategory());
        }

preparestatement输出执行的SQL_java_03

多对多关系

动态SQL:
if:

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

where:

标签会进行自动判断
如果任何条件都不成立,那么就在sql语句里就不会出现where关键字
如果有任何条件成立,会自动去掉多出来的 and 或者 or。

<select id="listProduct1" 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>

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>

choose标签:
相当于 switch 第一个条件成立了,就不再执行下一条件

<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>

bind标签: 相当于concat 字符串连接。

<!-- 本来的模糊查询方式 -->
<!--         <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>

对于事务,Mysql的引擎engine=innodb,只有当表的类型是INNODB的时候,才支持事务。

分页查找:
SQL语句:

<select id="listCategoryfenye" resultType="Category">
            select * from   category_
                <if test="start!=null and count!=null">
                    limit #{start},#{count}
                </if>
        </select>

输出语句:

Map<String,Object> params = new HashMap<>();
       
        params.put("start", 0);
        params.put("count", 5);
        List<Category>  cs =session.selectList("listCategoryfenye", params);
        for (Category c : cs) {
            System.out.println(c);
        }

分页插件:
PageHelper
需要导包:
pagehelper-5.1.0-beta2.jar,jsqlparser-1.0.jar
也可以在Maven仓库导相应的包
要在配置文件mybatis-config.xml加

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
             
        </plugin>
    </plugins>

表示开启pagehelper插件
在Category.xml中的相应的查询:

<select id="listCategoryfenye" resultType="Category">
            select * from   category_
        </select>

在执行查询语句之前加入:PageHelper.offsetPage(0, 5);

PageHelper.offsetPage(0, 5);
        List<Category>  cs =session.selectList("listCategoryfenye");
        for (Category c : cs) {
            System.out.println(c);
        }

结果依旧可以分页查询到:

preparestatement输出执行的SQL_mysql_04

还可以查询到总数等数据:

PageHelper.offsetPage(0, 5);
        List<Category>  cs =session.selectList("listCategoryfenye");
        for (Category c : cs) {
            System.out.println(c);
        }
        PageInfo<Category> pageInfo = new PageInfo<>(cs);
        System.out.println("总数:"+pageInfo.getTotal());
        System.out.println(pageInfo);