博客
关于我
Mybatis老手复习文档
阅读量:443 次
发布时间:2019-03-06

本文共 2943 字,大约阅读时间需要 9 分钟。

MyBatis学习笔记

初识MyBatis

学习MyBatis是每个开发者都必须经历的阶段。虽然我之前在学习JPA+Hibernate时已经积累了一定的经验,但此次重新接触MyBatis让我对持久层框架有了更深入的理解。

MyBatis的优势

  • 灵活性:MyBatis在动态SQL方面的表现尤为突出,能够处理各种复杂的业务逻辑,极大地提升了代码的灵活性。
  • 效率:虽然有人认为MyBatis的效率不如JPA,但通过合理的配置和使用技巧,MyBatis在特定场景下表现依然出色。

MyBatis的开始

配置文件mybatis-config.xml

简单的MyBatis例子

package com.pipihao.pojo;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;import java.util.Date;@Data@NoArgsConstructor@AllArgsConstructorpublic class Blog implements Serializable {    private String id;    private String title;    private String author;    private Date createTime;    private int view;}

配置映射

在MyBatis中,字段名与数据库字段名的命名差异通常会通过配置来解决。例如,数据库中的create_time可以映射到Java类中的createTime

日志配置

分页配置

MyBatis支持两种分页方式:原生分页和RowBunds分页。对于原生分页,直接在SQL中使用LIMITOFFSET即可。

RowBunds分页通过在Mapper接口中传递RowBunds对象来实现。

RowBounds rowBounds = new RowBounds(0, 2);List
blogs = mapper.findBlogById(rowBounds);

注解开发

在MyBatis中,注解开发可以与XML配置相结合,提供更灵活的开发体验。

public interface StudentMapper {    @Select("select * from student where id = #{sid}")    Students getStudentById(@Param("sid") int sid);}

多对一和一对多处理

多对一

一对多

动态SQL

动态SQL在MyBatis中通过<sql>标签实现,支持iftrimforeach等功能。

insert into blog (id,title,author,create_time,view) values (#{id},#{title},#{author},#{createTime},#{view})
and title = #{title}
and author = #{author}
update blog
title = #{title}
author = #{author}
where id = #{id}

缓存

MyBatis支持一级缓存和二级缓存。

一级缓存

默认启用,仅在一个SqlSession中有效。

二级缓存

通过@Cache注解或 <cache>标签实现。

总结

MyBatis作为一个灵活且强大的持久层框架,在动态SQL、缓存等方面表现出色。虽然JPA+Hibernate在对象关系映射方面更为强大,但MyBatis在小型项目中依然是一个不错的选择。

在实际开发中,建议结合PageHelper等工具来提升分页性能,并合理使用注解开发与XML配置相结合的方式,以提升开发效率。

转载地址:http://wfkfz.baihongyu.com/

你可能感兴趣的文章
notepad++最详情汇总
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>