A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Tong心未泯 初级黑马   /  2018-3-15 17:56  /  717 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

今天主要内容
1、输入映射和输出映射
a) 输入参数映射
b) 返回值映射
2、动态sql
3、关联查询
a) 一对一关联
b) 一对多关联
4、Mybatis整合spring

     一 输入映射和输出映射
  1.输入参数映射
               parameterType
*简单类型  #{任意} ${value}
*简单Pojo #{属性} ${属性}
*包装类Pojo #{属性.属性..} ${属性.属性..}   ogml表达式
*扩展 输入参类型为Map
#{key} ${key}

  *知道
    输入参数类型那个可以是多个但是需要使用@Param("");
     原理让mybatis底层将形参放到Map中去
2.返回值映射
    resultType
       可以返回Pojo,要求Pojo的属性的名称要和查询出来的结果集中的字段保持一致.
       返回简单类型,如果Sql执行的结果仅仅包含一行一列,就可以实现简单类型

         resultMap
                  resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
   
resultMap 和resultType
1.如果返回值是简单类型,使用resultType
2.如果返回值是简单Pojo类 使用resultTyp
3..如果返回值是简单Pojo的集合 使用resultType
4.如果返回值是包装类Pojo类 使用resultMap
  二.动态Sql      
      if拼接Sql语句
     foreach标签  适合用于类似查询多个id
      动态Sql片段
      可以将一些公共Sql片段提取出来.
      include 可以引用一些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.itheima.mapper.UserMapper" >
    <!-- sql片段 -->
   <sql id="sql">
       o.id,o.user_id,
    </sql>

   <!-- -查询到订单用户信息使用 resultMap -->
    <resultMap type="Orders" id="orderUserResulutMap">
      <id column="id" property="id"></id>
      <result column="user_id" property="userId"/>
      <result column="nubmer" property="nubmer"/>
      <result column="note" property="note"/>
      <result column="createtime" property="createtime"/>
      <!-- 一对一关联映射 -->
      <!--
        property :Orders 对象的user属性
        javaType:user属性的对应的类型
       -->
       <association property="user" javaType="com.itheima.pojo.User">
          <!-- column :user表 的主键对应的列  property:use 对象中的id属性 -->
             <id column="user_id" property="id" />
             <result column="username" property="username"/>
             <result column="address" property="address"/>
       </association>
     </resultMap>
        <select id="findOrdersWithUserResultMap" resultMap="orderUserResulutMap">
        SELECT
            <include refid="sql"></include>
            o.number,
            o.createtime,
            o.note,
            u.username,
            u.address
        FROM
            orders o
        JOIN `user` u ON u.id = o.user_id
    </select>
    <resultMap type="user" id="findUserWithOrder">
         <id column="id" property="id"/>
         <result column="username" property="username"/>
         <result column="sex" property="sex"/>
         <result column="birthday" property="birthday"/>
         <result column="address" property="address"/>
         <!-- 一对多关联 -->
         <collection property="orders" ofType="orders">
            <id  column="oid"  property="id" />
            <result column="number" property="number"/>
            <result column="createtime" property="createtime"/>
         </collection>
    </resultMap>
     <select id="findUserWithordes" resultMap="findUserWithOrder">
       SELECT u.*,o.createtime,o.id oid,o.number FROM USER u  LEFT JOIN orders o ON u.id=o.user_id
     </select>
   <!-- 查询id  利用where  if标签 -->
    <select  id="fingUserbywhere" parameterType="user" resultType="user" >
          select * from user
          <where>   <!-- where标签会自动把满足第一个条件的and 去掉 -->
            <if test="id!=null">
              and  id=#{id}
            </if>
            <if test="username!=null and username !=''">
               and username like '%${username}%'
            </if>
          </where>
    </select>
    <!-- 动态SQL片段  foreach标签测试 -->
    <select id="findUserByIds" resultType="user" parameterType="queryvo">
      select *from user
      <where>
        <!-- and id in (  1,10,21,23  ) -->
        <foreach collection="ids" item="id" open="and  id in (" close=")" separator=",">
        id=#{id}
        </foreach>
      </where>
    </select>
</mapper>



  四.spring整合mybatis
AOP:
IOC:spring来管理资源(对象)
    把SqlSessionFactor SQLSession 交给spring管理
    Dao产生的bean
开发方式
  传统Dao开发
   基于Mapper代理方法

1.spring整合mybatis传统开发:(了解)
*定义Dao接口
*定义一个类extends SqlSessionDaoSupport implements UserDao{
//在方法中获取SqlSession
getSqlSession();
  }

2.spring整合mybatis基于mapper代理开发:(重点掌握,开发中用)

步骤:
思路:将SqlSessionFactory Mappe接口代理对象r交给spring管理

1.搭建环境
2.创建spring的配置文件呢applicationContext.xml
*配置文件加载
*配置数据源 c3p0 dbcp ..drduid bonecp.
*配置SqlSessionFactoryBean
*注入数据源
*注入mybatis全局配置文件
*创建mybatis全局配置文件SqlMapConfig.xml
别名(typeAliases)
*MapperScannerConfigurer
        注入扫描的包,一次性将包下的Mapper接口生成代理对象并且纳入spring容器
       代理对象的id就是Mapper接口的名首字母小写
      *要求Mapper.xml 和Mapper接口同名通路径

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.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}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    <!-- sqlSessonFactory的配置 -->
      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <!-- 配置连接池 -->
         <property name="dataSource" ref="dataSource"></property>
          <!--加载配置文件 -->
         <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
      </bean>
    <!-- mapper代理形式dao的配置 -->
    <!-- 第一种方法,配置代理对象 -->
    <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        设置代理的mapper接口
        <property name="mapperInterface" value="cn.itheima.mybatis.mapper.UserMapper"></property>
        注入sqlSessionFactory
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean> -->
    <!-- 配置包扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置要扫描的包 ,如果扫描多个包使用半角逗号分隔-->
        <property name="basePackage" value="com.itheima.mapper"/>
    </bean>
</beans>
SqlMapConfig.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>
    <!-- 配置pojo别名 -->
    <typeAliases>
        <package name="com.itheima.pojo"/>
    </typeAliases>
</configuration>
    六.逆向工程
  只针对单表操作
          导入相关代码.修改数据库用户,密码.以及生成位置,根据那个表生成
GeneratorSqlmap.java

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

public class GeneratorSqlmap {
    public void generator() throws Exception{
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指定 逆向工程配置文件
        File configFile = new File("generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,
                callback, warnings);
        myBatisGenerator.generate(null);
    }
    public static void main(String[] args) throws Exception {
        try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

   generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/springmvc" userId="root"
            password="123456">
        </jdbcConnection>
        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"
            userId="yycg"
            password="yycg">
        </jdbcConnection> -->

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.itheima.springmvc.po"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.itheima.springmvc.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.itheima.springmvc.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table schema="" tableName="user"></table>
        <!-- <table schema="" tableName="orders"></table> -->
        <table schema="" tableName="items"></table>
<!--        <table schema="" tableName="orderdetail"></table> -->
        
        <!-- 有些表的字段需要指定java类型
         <table schema="" tableName="">
            <columnOverride column="" javaType="" />
        </table> -->
    </context>
</generatorConfiguration>

   今日总结
1.paramterType
简单类型 #{任意} ${value}
简单pojo #{属性} ${属性}
Map #{key} ${key}
包装类型Pojo #{属性..} ${属性..}
2.resultType
  返回Pojo:字段要和Pojo属性保持一致。
  简单类型:SQL执行的结果仅仅包含一行一列就是使用简单类型。
resultMap
3.动态SQL
<if test="">
</if>
<where>
<foreach>
<sql>
<include>
4.多表关联查询
1:1
  查询订单关联查询用户
  resultType
  resultMap
   *分析模型之间关系,建立关系。
    1:1 在一方创建另一方的引用
    1:n 在一方创建另一方的集合
   *在映射文件中编写SQL
   *如何使用resultMap完成映射
    1:1 assosiaction porperty="引用" javaType="引用类型"
    1:n collection porperty="集合的引用" ofType="集合中元素的类型"
1:n
5. ssm整合
   spring管理mybatis
  SQLSessionFactory
  Mapper接口代理对象
*在classpath下面applicationContext.xml
  *配置属性文件加载
  *配置数据源
  *配置SQLSessionFactoryBean
   *注入数据源
   *注入mybatis全局配置文件
  *创建sqlMapConfig.xml
      别名
  *MapperScannerConfiguer
   注入扫描包
   要求Mapper接口映射同名同路径
如何获取代理。
  加载spring容器,使用getBean获取

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马