Mybatis第二天

1.Mybatis

1.mybatis别名

a)内置别名
常用基本类型 和包装类型 8 个 以及集合类型

b)自定义别名
(1)单独配置类的实现

<typeAliases>
 <typeAlias type="cn.itsource.mybatis.query.ProductQuery" alias="productQuery"></typeAlias>
 <typeAlias type="cn.itsource.mybatis.domain.Product" alias="product"></typeAlias>
</typeAliases>      

(2)配置包形式 推荐

<typeAliases>
	 <package name="cn.itsource.mybatis.query"></package>
     <package name="cn.itsource.mybatis.domain"></package>
</typeAliases>

2.映射器Mapper

昨天:IProductDao(接口) – ProductDaoImpl 实现

今天: ProductMapper(接口) -->不写实现 (mybatis底层会采用动态代理模式 会跟我生成实现)

步骤:

​ (1) 创建项目 配置mybatis-config.xml 和昨天一样

​ (2) 创建接ProductMapper(XXXXMapper) 里面定义一个方法findAll -->以前dao层/mapper层

(3) 在对应的ProductMapper.xml namespace 和 标签里面id
(namespace+id) == (ProductMapper包路径+方法)

<?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="cn.itsource._01_mapper.mapper.ProductMapper">
    <select id="findAll"  resultType="product">
        select * from product
    </select>  
</mapper>

(4) 测试类 测试Mapper

 @Test
    public void testMapper(){
        //得到mapper --映射器 (动态代理)
        ProductMapper productMapper = MybatisUtil.INSTANCE.getSqlSession().
                getMapper(ProductMapper.class);

        for (Product product : productMapper.findAll()) {
            System.out.println(product);
        }

    }

3.高级查询

1.模糊查询写法一:(存在sql注入的问题)

 <if test="productName != null">
                and productName like '%${productName}%'
     </if>

2.模糊查询写法二:(用concat进行转义)

 <if test="productName != null">
                and productName like concat('%',#{productName},'%')
      </if>

1.条件查询写法一:
用特殊符号转义(lt,le…)

<if test="minPrice != null and  maxPrice != null">
                and salePrice > #{minPrice} and salePrice &lt; #{maxPrice}
</if>

2.条件查询写法二:
用xml中的CDATA

 <if test="minPrice != null and  maxPrice != null">
                <![CDATA[
                  and salePrice > #{minPrice} and salePrice <= #{maxPrice}
                ]]>
    		</if>

4.结果映射

使用场景:当数据库里面的列和对象里面的字段不统一的时候

(1)使用别名就可以解决

 <select id="findAll"  resultType="product">
            select id,productName pName,salePrice,costPrice,cutoff from product
 </select>

(2)返回Map解决映射问题

<select id="findAll"  resultMap="productMap">
        select id,productName,salePrice,costPrice,cutoff from product
    </select>
    <resultMap id="productMap" type="product">
        <!-- id:主键
            property:类里面的属性
            column:查询列名称
          -->
        <id property="id" column="id"></id>
        <result property="pName" column="productName"></result>
        <result property="salePrice" column="salePrice"></result>
    </resultMap>

5.关系处理

1.对一方处理(多对一/一对多)

嵌套结果: 只发送一条sql

 <resultMap id="productMap" type="product">
        <id column="id" property="id"></id>
        <result column="productName" property="pName"></result>
        <result column="salePrice" property="salePrice"></result>
        <result column="costPrice" property="costPrice"></result>
        <result column="cutoff" property="cutoff"></result>
        <!--处理一方-->
        <association property="dir" javaType="productDir">
            <id column="did" property="id"></id>
            <result column="dname" property="dirName"></result>
        </association>
      <!--  扩展一 另一种处理一方的写法
      <result property="dir.id" column="did"></result>
     <result property="dir.dirName" column="dname"></result>-->
    </resultMap>
<select id="findAll" resultMap="productMap">
    select
            p.id,
            p.productName,
            p.salePrice,
            p.costPrice,
            p.cutoff,
            dir.id did,
            dir.dirName dname
    FROM
            product p
    JOIN productDir dir ON p.dir_id=dir.id

    </select>

嵌套查询:发送多sql语句(1+n条sql)

 <select id="findAll" resultMap="productMap">
        select * from product
    </select>
    <resultMap id="productMap" type="product">
        <id column="id" property="id"></id>
        <result column="productName" property="pName"></result>
        <result column="salePrice" property="salePrice"></result>
        <result column="costPrice" property="costPrice"></result>
        <result column="cutoff" property="cutoff"></result>
        <!--根据上面查询dir_id在去查询 分类对象-->
        <association property="dir" column="dir_id" javaType="productDir" select="selectDir">
        </association>
    </resultMap>
    <select id="selectDir" parameterType="long" resultType="ProductDir">
        select * from productDir where id=#{dir_id}

    </select>

2.对多方进行处理(一对多/多对多)

1.嵌套结果(如果用嵌套结果进行分页查询的话是有些小问题的,所以如果要使用分页的话推荐使用嵌套查询)

<select id="findAll" resultMap="productDirMap">
      select dir.id ,dir.dirName,
        p.id pid,p.productName pName,p.salePrice,p.costPrice,p.cutoff
        from productDir dir join product p
        on dir.id = p.dir_id
    </select>
<resultMap id="productDirMap" type="productDir">
        <id property="id" column="id"></id>
        <result property="dirName" column="dirName"></result>
        <collection property="products" ofType="product">
            <id property="id" column="pid"></id>
            <id property="id" column="pid"></id>
            <result property="pName" column="pName"></result>
            <result property="salePrice" column="salePrice"></result>
            <result property="costPrice" column="costPrice"></result>
        </collection>
    </resultMap>

嵌套查询+分页查询

<select id="findAll" resultMap="productDirMap">
        select dir.id,dir.dirName from productDir dir limit 0,2
    </select>
    <resultMap id="productDirMap" type="productDir">
        <id property="id" column="id"></id>
        <result property="dirName" column="dirName"></result>
        <collection property="products" column="id" ofType="product" select="selectProducts"></collection>
    </resultMap>
    <select id="selectProducts" parameterType="long" resultType="product">
         select id,productName pName,salePrice,costPrice,cutoff from product where dir_id = #{dir_id}
    </select>

3.延迟加载(了解)

意思就是:使用的时候才去加载

4.缓存(了解)

mybatis 支持缓存 (一级缓存 和二级缓存)

redis(nosql的数据库 做缓存)

1.mybatis一级缓存

属于sqlSession级别缓存(entityManager类似)

命中条件:

​ mybatis一级缓存 命中(同一个SqlSessionFactory 同一个SqlSession 同一个ID)

public void testMapper(){
        //得到mapper --映射器 (动态代理)

        SqlSession sqlSession1 =  MybatisUtil.INSTANCE.getSqlSession();
        //mybatis一级缓存 命中(同一个SqlSessionFactory 同一个SqlSession 同一个ID)
        ProductMapper mapper1 = sqlSession1.getMapper(ProductMapper.class);
        System.out.println(mapper1.findOne(19L));

        ProductMapper mapper2 = sqlSession1.getMapper(ProductMapper.class);
        System.out.println(mapper2.findOne(19L));

    }
2.mybatis二级缓存

命中条件: 同一个SqlSessionFactory 不同的SqlSession 同一个ID

面试题:

​什么叫序列化:
把对象转换成二进制的信息 这个过程
​为什么需要序列化:
用在网络传输
反序列化:
把二进制内容转成对象的形式 这个过程
使用方法:
Mapper那层要实现序列化接口
xml那里要写一个

<!--使用缓存-->
    <cache></cache>

2.SSM整合

1.整合步骤

​ (1)创建项目–web项目 (maven/普通web)

​ (2)导入三个框架的jar包
在这里插入图片描述

​ (3)配置文件

​ applicationContext.xml 里面配置spring+mybatis

<?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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--扫描service 自动注入到spring  service注解 -->
    <context:component-scan base-package="cn.itsource.ssm.service"></context:component-scan>
    <!-- db.proproperties  dataSource  sqlSessionFactory transaction mapper-->

    <!--引入jdbc.properties-->
    <context:property-placeholder location="classpath:db.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 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*Mapper.xml"></property>
        <property name="typeAliasesPackage">
            <value>
                cn.itsource.ssm.domain
            </value>
        </property>
    </bean>

    <!-- 把产生mapper 交给 spring-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.itsource.ssm.mapper"></property>
    </bean>

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

</beans>

applicationCotnext-mvc.xml --配置springmvc

<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描controller-->
    <context:component-scan base-package="cn.itsource.ssm.web.controller" />
    <!--静态资源处理-->
    <mvc:default-servlet-handler />
    <!--识别@RequestMapping等注解支持-->
    <mvc:annotation-driven />
    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>


</beans>

db.properties 配置数据库

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

web.xml --配置web的内容

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--
      监听器

  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--核心控制器-->
    <servlet>
        <servlet-name>dispatchServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatchServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--编码过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

log4j.properties配置日志框架

log4j.rootLogger=ERROR, stdout
#log4j.rootLogger=NONE
log4j.logger.cn.itsource=TRACE

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

3.常见错误

1.写的mapper文件没有在配置文件里面注册

java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for cn.itsource.mybatis.crud.UserMapper.createTable

2.返回的结果是List,而需要的是一个对象

org.apache.ibatis.executor.ExecutorException: Statement returned more than one row, where no more than one was expected.

Product findAll()
<select id="findAll" 
   resultType="cn.itsource.mybatis.c_manytoone.Dept"		parameterType="long">		
select id,name from t_dept where id=#{id}	
</select>

3.没有序列化异常

使用二级缓存的时候,没有去实现序列化接口

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值