MyBatis&&ssm项目集成

                MyBatis&&ssm项目集成

一.mapper映射
    1.准备接口 EmployeeMapper
    2.准备xml EmployeeMapper.xml
    3.测试的完成
二.高级查询
三.关系配置(重难点)
    1.多对一
        1.1 domain准备
        1.2 关系映射 - 嵌套结果
        1.3 关系映射 - 嵌套查询
    2.一对多的配置
        2.1 相应的domain准备
        2.2 嵌套结果
        2.3 - 嵌套查询
四.SSM三大框架集成
    4.1 导包
    4.2 jdbc.properties
    4.3 applicatinContext.xml
扩展:
    多对一映射的野方法
    一对多分页的坑

一.mapper映射

我们只需要写接口,实现由MyBatis自己完成
xml中的命名空间与接口的全限定名一致
接口中的方法名与xml的sql的id一致

1.准备接口 EmployeeMapper

package cn.itsource._01_mapper.mapper;
...
public interface EmployeeMapper {
    Employee findOne(Long id);
    //@Select("select * from employee") : 太复杂的解决不了
    List<Employee> findAll();
}

2.准备xml EmployeeMapper.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">

<!--  这里的id必需和方法名对应 -->
<select id="findOne" parameterType="long" resultType="cn.itsource._01_mapper.domain.Employee">
    select * from employee where id= #{id}
</select>

<!--查询所有-->
<select id="findAll" resultType="cn.itsource._01_mapper.domain.Employee">
    select * from employee
</select>


3.测试的完成

@Test
public void testMapper() throws Exception{
    //1.拿到session对象
    SqlSession session = MyBatisUtils.openSession();
    //2.拿到mapper的实现 (MyBatis自动帮我们实现了功能)
    EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
    //3.直接执行方法
    Employee employee = mapper.findOne(1L);
    System.out.println(employee);

    session.close();
}

结构如下图

二.高级查询

模糊查询使用concat concat("%",#{name},"%")
特殊字符使用转义或者CDATA段
    &lt; 代表小于
    <![CDATA[ ... ]]>
每个条件都需要if判断(有这个条件才进行过滤)
    `<if test="条件一 and/or 条件二">
在过滤前加上 where, 把第一个and替换成where
如果遇到重复的SQL,可以使用 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">

<!--准备一个代码块-->
<sql id="whereSql">
    <where>
        <if test="name!=null and name!=''">
            and name like concat("%",#{name},"%")
        </if>
        <if test="minAge!=null">
            and age >= #{minAge}
        </if>
        <if test="maxAge!=null">
            <![CDATA[
               and age <= #{maxAge}
             ]]>
        </if>
    </where>
</sql>

<!--查询一共多少条数据-->
<select id="getCount" resultType="long" parameterType="cn.itsource._01_mapper.query.EmployeeQuery">
  select count(*) from employee
  <include refid="whereSql" />
</select>
<!--
    条件查询的语句
        CDATA:区中的数据不会被识别为语法
 -->
<select id="queryAll" parameterType="cn.itsource._01_mapper.query.EmployeeQuery"
        resultType="cn.itsource._01_mapper.domain.Employee">
    select * from employee
    <include refid="whereSql" />
</select>

<!--  这里的id必需和方法名对应 -->
<select id="findOne" parameterType="long" resultType="cn.itsource._01_mapper.domain.Employee">
    select * from employee where id= #{id}
</select>

<!--查询所有-->
<select id="findAll" resultType="cn.itsource._01_mapper.domain.Employee">
    select * from employee
</select>

三.关系配置(重难点)
1.多对一
1.1 domain准备

Product

public class Product {

private Long id;
private String name;
//多对一(多个产品对应一个分类)
private ProductDir dir;

//gettersetter与toString省略

ProductDir

public class ProductDir {

private Long id;
private String name;
//gettersetter与toString省略

}

1.2 关系映射 - 嵌套结果

一条SQL查询所有数据(容易出现相同的列名,因此我们开发的时候尽量要为这些列取相应的别名),mybatis再帮我们把数据整理出来。

必需使用resultMap进行手动映射
association 用于进行对象的关连
    使用后自动映射失效
    单独配置对象中的属性

<!--
    自己写代码完成手动映射
    resultMap:结果映射 id:名称 type:映射的对象类型
        result:某一个属性的映射 property:类型的属性 column:表中的列
    association:关联(如果要关连一个对象就使用它) -> 自动映射就失效了
            property:属性名   column:列名   javaType:属性的类型
            property,column:这两个东西可以让名称对应
            javaType加上里面的标签:对应上类型与类型里面的数据
        理解:在Product对象中有一个ProductDir类型的属性:dir,这个dir中有两个属性,一个是id(对应查询结果的did),一个是name,...
-->
<resultMap id="productMap" type="cn.itsource._02_many2one_result.Product">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <association property="dir" javaType="cn.itsource._02_many2one_result.ProductDir">
        <id property="id" column="did" />
        <result property="name" column="dname" />
    </association>
</resultMap>

<!--
    resultMap:找到对应的手动映射
-->
<select id="findAll" resultMap="productMap">
   select p.id,p.name,dir.id did,dir.name dname from t_product p
        LEFT JOIN t_productdir dir
        ON dir.id = p.dir_id
</select>

1.3 关系映射 - 嵌套查询

先准备一条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">

<!-- 手动映射 -->
<resultMap id="productMap" type="cn.itsource._03_many2one_search.Product">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <!--设置关连映射
        select="findDirById" : 找到对应的查询语句
            如果调用的是其它的xml中的查询: select="命名空间.id的值"
    -->
    <association property="dir" column="dir_id" select="findDirById"
                 javaType="cn.itsource._03_many2one_search.ProductDir"></association>
</resultMap>

<!--根据id获取到相应的类型  parameterType="long"获取到的是column中的值 -->
<select id="findDirById" parameterType="long" resultType="cn.itsource._03_many2one_search.ProductDir">
    select * from t_productdir where id=#{id}
</select>

<select id="findAll" resultMap="productMap">
  select * from t_product
</select>

2.一对多的配置
2.1 相应的domain准备

Product

public class Product {

private Long id;
private String name;
//gettersetter与toString省略

ProductDir

public class ProductDir {

private Long id;
private String name;
 //一对多:一个类型对应多个产品
private List<Product> products = new ArrayList<>();
//gettersetter与toString省略

}

2.2 嵌套结果

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

<!--
    手动映射 association:代表关连的是一个对象
        collection:集合(拿到多方):使用后自动映射失效
            property:属性名
            ofType:代表这个属性中每一个对象的类型
-->
<resultMap id="productDirMap" type="cn.itsource._04_one2many_result.ProductDir">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <collection property="products" ofType="cn.itsource._04_one2many_result.Product">
        <id property="id" column="pid" />
        <result property="name" column="pname" />
    </collection>
</resultMap>

<select id="findAll" resultMap="productDirMap">
    select dir.id,dir.name,p.id pid,p.name pname from t_productdir dir LEFT JOIN t_product p
      ON p.dir_id = dir.id
</select>

2.3 - 嵌套查询

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

<!--
    手动映射 association:代表关连的是一个对象
        collection:集合(拿到多方):使用后自动映射失效
            property:属性名
            ofType:代表这个属性中每一个对象的类型
            select:获取到相应的SQL
-->
<resultMap id="productDirMap" type="cn.itsource._05_one2many_search.ProductDir">
    <id property="id" column="id" />
    <result property="name" column="name" />
    <collection property="products" column="id"  select="getProductByDirId"
                ofType="cn.itsource._05_one2many_search.Product" >
    </collection>
</resultMap>

<select id="getProductByDirId" parameterType="long" resultType="cn.itsource._05_one2many_search.Product">
    select * from t_product where dir_id = #{id}
</select>

<select id="findAll" resultMap="productDirMap">
    select * from t_productdir
</select>

四.SSM三大框架集成

①.导包
②.基本结构搭建
③.集成步骤

db.properties
dataSource
SqlSessionFactory
Mapper映射器
mapper,service
TX事务
Controller
4.1 导包

Spring的包,Spring的依赖包,SpringMVC的包(json支持包),mybatis的包,mybatis与Spring的集成包 image

4.2 jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=123456

4.3 applicatinContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--扫描service-->
<context:component-scan base-package="cn.itsource.ssm.service" />

<!--
    ①.jdbc.properties -> ②.DataSource -> ③.SqlSessionFactory -> ④.Mapper实现
        -> ⑤.Service/TX事务 -> ⑥.集成SpringMVC
-->
<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--创建dataSource-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!--
    配置SqlSessionFactory -> SqlSessionFactoryBean
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--连接池-->
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*Mapper.xml" />
    <!--typeAliasesPackage:这个包中所的值都会取相应的别名-->
    <property name="typeAliasesPackage">
        <value>
            cn.itsource.ssm.domain
            cn.itsource.ssm.query
        </value>
    </property>
</bean>

<!--
    让Spring帮我们生成Mapper
    mapperInterface:代表你要映射的接口类型
<bean id="employeeMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    <property name="mapperInterface" value="cn.itsource.ssm.mapper.EmployeeMapper" />
</bean>
-->

<!-- 一劳永逸
    Mapper(映射)Scanner(扫描)Configurer(配置)
    basePackage:扫描的包(会用对象的类都创建实现)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.itsource.ssm.mapper" />
</bean>


<!--事务配置-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<!--开启事务注解的支持,默认会去找一个名称叫做transactionManager的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager" />

扩展
多对一映射的野方法

<?xml version="1.0" encoding="UTF-8" ?>
<resultMap id="productMap" type="cn.itsource._06_many2one_haha.Product">
    <result property="dir.id" column="did" />
    <result property="dir.name" column="dname" />
</resultMap>

<!--
    resultMap:找到对应的手动映射
-->
<select id="findAll" resultMap="productMap">
   select p.id,p.name,dir.id did,dir.name dname from t_product p
        LEFT JOIN t_productdir dir
        ON dir.id = p.dir_id
</select>


猜你喜欢

转载自www.cnblogs.com/1999wang/p/11392071.html