mybatis-入门(2)

Lombok的使用

在idea中安装lombok
在这里插入图片描述

在pom.xml文件插入依赖

		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
@ExtensionMethod (Experimental, activate manually in plugin settings)
Lombok config system

多对一查询方式

按照查询嵌套处理

<!--
        思路:
        查询所有的产品信息
        根据查询出来产品信息的checkPeople,寻找对应的检查人员  
        嵌套查询
    -->
    <select id="getProduct" resultMap="ProductPeople">
        select * from product;
    </select>
    <resultMap id="ProductPeople" type="product">
        <result property="productNumber" column="product_number"></result>
        <result property="torfhege" column="TORFhege"></result>
        <result property="productType" column="product_type"></result>
        <!--
            对象:association
            集合:collection
        -->
        <association property="checkPeople" column="check_people" javaType="TestPersonnel" select="getPersonal"></association>
<!--        <collection property=""></collection>-->
    </resultMap>

    <select id="getPersonal" resultType="testPersonnel">
        select * from test_personnel where testpeople_number=#{testpeopleNumber};
    </select>

按照结果嵌套查询

<!--按照结果嵌套查询-->
    <select id="getProduct2" resultMap="ProductTestpeople">
        SELECT p.product_number pnumber,p.check_people pcpeople,t.name tname
        FROM test_personnel t,product p
        WHERE t.`testpeople_number` = p.`check_people`
    </select>
    <resultMap id="ProductTestpeople" type="product">
        <result property="productNumber" column="pnumber"></result>
        <association property="checkPeople" javaType="testPersonnel">
            <result property="name" column="tname"></result>
        </association>
    </resultMap>

一对多查询

按结果嵌套查询

<!--按结果嵌套查询-->
    <select id="getTestPersonnel" resultMap="TestPeopleStudent">
        select *
        FROM product p,test_personnel t
        WHERE p.check_people=t.testpeople_number AND t.testpeople_number = #{pid}
    </select>
    <resultMap id="TestPeopleStudent" type="testPersonnel">
        <result property="testpeopleNumber" column="testpeople_number"/>
        <result property="name" column="name"/>
        <result property="password" column="password"/>
        <result property="job" column="job"/>
        <result property="gender" column="gender"/>
        <result property="phoneNumber" column="phone_number"/>
        <!--
        javaType=""指定属性的类型
        集合中的泛型用ofType获取
        -->
        <collection property="products" ofType="product">
            <result property="productNumber" column="product_number"/>
            <result property="checkPeople" column="check_people"/>
            <result property="torfhege" column="TORFhege"/>
            <result property="productType" column="product_type"/>
        </collection>
    </resultMap>

按查询嵌套处理

 <!--按查询嵌套处理-->
    <select id="getTestPersonnel2" resultMap="TestPeopleStudent2">
        select * from test_personnel t where t.testpeople_number = #{pid}
    </select>
    <resultMap id="TestPeopleStudent2" type="testPersonnel">
        <result property="testpeopleNumber" column="testpeople_number"></result>
        <result property="phoneNumber" column="phone_number"></result>
        <collection property="products" javaType="ArrayList" ofType="product" column="testpeople_number" select="getProductByID"></collection>
    </resultMap>
    <!--
    testpeople_number  对应的是resultMap中集合collection传进去的值(column="testpeople_number"-->
    <select id="getProductByID" resultType="product">
        select * from product where check_people = #{testpeople_number}
    </select>
小结

对象:association 多对一
集合:collection 一对多
javaType=""指定属性的类型
ofType 映射到List或集合中的泛型获取

  • 保证SQL语句的可读性
  • 注意一对一和多对一,属性名和字段的问题
  • 记得使用日志Log4j

mysql引擎
InnoDB底层原理
索引
索引优化

动态SQL

导入包
编写配置文件
写实体类
编写mapper接口和mapper。xml文件

IF

这条语句提供了可选的查找文本功能

mapper接口

    List<TestPersonnel> getTestPersonnel3(Map map);

接口实现

 <select id="getTestPersonnel3" parameterType="map" resultType="testPersonnel">
        select * from test_personnel
        where 1=1
        <if test="name != null">
            and name = #{name}
        </if>
        <if test="password != null">
            and password = #{password}
        </if>
    </select>

测试

void getTestpeople(){
        Map map = new HashMap();
        map.put("name","wzh");
        map.put("password","123123");
        List<TestPersonnel> testPersonnel3 = testPersonnelMapper.getTestPersonnel3(map);
        for (TestPersonnel personnel : testPersonnel3) {
            System.out.println(personnel);
        }
    }

choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

 <select id="getTestPersonnel3" parameterType="map" resultType="testPersonnel">
        select * from test_personnel
        <where>
            <choose>
                <when test="name != null">
                    and name = #{name}
                </when>
                <when test="password != null">
                    and password = #{password}
                </when>
                <otherwise>
                    and job = #{job}
                </otherwise>
            </choose>
        </where>
    </select>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

trim、where、set

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
动态SQL本质还是SQL语句,只不过在SQL语句上可以执行逻辑判断

SQL片段

将一部分功能代码抽取出来方便复用

<sql id="chooseWhen">
        <choose>
            <when test="name != null">
                and name = #{name}
            </when>
            <when test="password != null">
                and password = #{password}
            </when>
            <otherwise>
                and job = #{job}
            </otherwise>
        </choose>
    </sql>

复用

<select id="getTestPersonnel3" parameterType="map" resultType="testPersonnel">
        select * from test_personnel
        <where>
            <include refid="chooseWhen"></include>
        </where>
    </select>

不要再SQL片段中存在where

foreach

<select id="getTestPersonnelForeach" parameterType="map" resultType="testPersonnel">
        select * from test_personnel
        <where>
            testpeople_number IN
            <foreach  collection="ids" item="item"
                open ="(" separator="," close=")">
                #{item}
            </foreach>
        </where>
    </select>
    拼接成(123)的形式
    open =(’  代表用‘(’开头
    close = ‘)’ 代表用 ‘)’结尾
    collection = 'ids'  是map中的集合
    item = “item” 是遍历出来的元素
    index = “index” 是索引(下标) 第几次运行

在写完SQL后再去拼接SQL

缓存

	查询  --- 数据库   耗费资源
	把一次查询的结果把他暂存在一个地方     内存--》缓存
	
我们再次相同数据查询时,走缓存就可以了
映射语句文件中的所有 select 语句的结果将会被缓存。
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
  • 什么是缓存
    存在内存中的临时数据
    将用户经常查询的数据放在缓存中,用户查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

  • 为什么使用缓存
    减少和数据库交互次数,减少系统开销,提高系统效率

  • 什么样的数据能使用缓存
    经常查询并且不经常改变的数据

Mybatis缓存

  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存,缓存可以极大的提升查询效率。
  • Mybatis系统中默认定义了两级缓存;一级缓存和二级缓存
    默认情况下,只有一级缓存开启(Sqlsession级别的缓存,也称为本地缓存)
    二级缓存需要手动开启和配置。他是基于namespace级别的缓存
    为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
一级缓存

一级缓存也叫本地缓存:Sqlsession
与数据库同一次会话期间查询的数据会放在本地缓存中。
以后如果需要获取相同数据,直接从缓存中拿,没必要再去查询数据库

测试步骤
1、打开日志
2、测试在一个Session中查询两次相同数据
3、查看日志输出

在这里插入图片描述
缓存失效情况:
查询不同的东西
增删改操作可能会改变原来数据,所以会刷新缓存
查询不同的Mapper.xml
手动清理缓存

@Test
    public void getCustomerById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        Customer customer = mapper.getCustomerByID("1000");
        System.out.println(customer);
        sqlSession.clearCache();//清理缓存
        Customer customer2 = mapper.getCustomerByID("1000");
        System.out.println(customer);
        System.out.println(customer==customer2);

        sqlSession.close();
    }

一级缓存默认开启,只在一次Sqlsession中有效(链接开启到关闭这个区间段)
一级缓存相当于Map

二级缓存

二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

工作机制

一个会话查询一条数据,这个数据就会放在当前会话的一级缓存中;
如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
新的会话查询信息,看可以从二级缓存中获取内容
不同的mapper查出的数据会放在自己对应的缓存(map)中;

步骤:
开启全局缓存

<!--开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>

在二级缓存使用中开启

<cache/>

或者自定义
<cache
  eviction="FIFO"
  flushInterval="60000"
  size="512"
  readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。

测试
我们需要将实体类序列化,否则就会报错

只要开启了二级缓存,同一个mapper下就有效
所有的数据都会先放在一级缓存中
只有当会话提交,或者关闭时,才会提交到二级缓存中

缓存原理

在这里插入图片描述

  • 先查二级缓存有没有
  • 再查一级缓存
  • 去查数据库

自定义缓存ehcache

导入包

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

再mapper中指定ehcache缓存实现

 <!--自定义缓存-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

配置ehcache.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--
       diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
       user.home – 用户主目录
       user.dir  – 用户当前工作目录
       java.io.tmpdir – 默认临时文件路径
     -->
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <!--
       defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
     -->
    <!--
      name:缓存名称。
      maxElementsInMemory:缓存最大数目
      maxElementsOnDisk:硬盘最大缓存个数。
      eternal:对象是否永久有效,一但设置了,timeout将不起作用。
      overflowToDisk:是否保存到磁盘,当系统当机时
      timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
      timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
      diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
      diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
      diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
      memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
      clearOnFlush:内存数量最大时是否清除。
      memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
      FIFO,first in first out,这个是大家最熟的,先进先出。
      LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
      LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>
 
    <cache
            name="cloud_user"
            eternal="false"
            maxElementsInMemory="5000"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="1800"
            memoryStoreEvictionPolicy="LRU"/>
 
</ehcache>

selectKey

在这里插入图片描述
允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。
useGeneratedKeys参数只针对 insert 语句生效,默认为 false;

<insert id="insertSysUniverseConfig" useGeneratedKeys="true" keyProperty="id" parameterType="com.tumo.tumomodel.domain.SysUniverseConfig">
		<selectKey keyProperty="id" resultType="java.lang.Integer" order="BEFORE">
			select nvl(max(id),0)+1 from HM_TX.HM_SYS.SYS_UNIVERSE_CONFIG
		</selectKey>

SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式。

属性 -描述:

① keyProperty : selectKey 语句结果应该被设置的目标属性。

② resultType:结果的类型。MyBatis 通常可以算出来,但是写上也没有问题。MyBatis 允许任何简单类型用作主键的类型,包括字符串。

③ order: 这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素-这和如 Oracle 数据库相似,可以在插入语句中嵌入序列调用。

④ statementType:和前面的相同,MyBatis 支持 STATEMENT ,PREPARED 和CALLABLE 语句的映射类型,分别代表PreparedStatement 和CallableStatement 类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值