• MyBatis详解


    MyBatis 是一款优秀的持久层框架,属于 ORM 映射。前身是 ibatis。

    MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis通过开发者书写SQL 语句,以及对象模型和关系模型的映射(ORM),完成对象模型和关系模型的数据转换。同时支持延迟加载,缓存,映射等。

    MyBatis 可以通过简单的XML 或注解来配置和映射对象模型和关系模型,从而完成对象数据和关系数据的转换。

    MyBatis 中文网:MyBatis中文网


    MyBatis 组成:

    核心对象:SqlSessionFactory SqlSession

    配置文件

    mybatis.cfg.xml -----> 主配置文件,用于配置数据源,链接各种 ORM 映射文件,以及实体类别名、日志等

    多个 ORM 映射文件 ----> 用于书写实体类和表的映射关系,操作数据库的 SQL 语句,以及配置持久接口


    mybatis 环境搭建

    导入依赖

    1.        mysql
    2.        mysql-connector-java
    3.        5.1.48
    4. org.mybatis
    5.         mybatis
    6.         3.5.9
    7.         org.mybatis
    8.         mybatis-typehandlers-jsr310
    9.         1.0.2

    1、建立实体类

    1. public class ProductBean {
    2.    //编号
    3.    private Integer id;
    4.    //商品名
    5.    private String name;
    6.    //生产日期
    7.    private LocalDate createDate;
    8.    //商品单价
    9.    private Integer price;
    10. }

    2、建立业务接口

    1. public interface IProductService {
    2.    public void add(ProductBean productBean);
    3. }

    3、建立Mapper接口

    1. public interface IProductMapper {
    2.    public void add(ProductBean productBean);
    3. }

    4、在 resources 目录中导入主配置文件 mybatis.cfg.xml

    1.  
    2.      "logImpl" value="STDOUT_LOGGING" />
    3.  
    4.  
    5.      <package name="com.project.bean"/>
    6.  
    7.   default="dev">  
    8.        "dev">  
    9.            "JDBC">  
    10.            "POOLED">
    11.            "driver" value="com.mysql.jdbc.Driver"/>
    12.            "url" value="jdbc:mysql://localhost:12345/shopDB?characterEncoding=utf-8&allowMultiQueries=true"/>
    13.            "username" value="root"/>
    14.            "password" value="123"/>
    15.              
    16.          
    17.      
    18.  
    19.  
    20.      <package name="com.project.mapper"/>
    21.  
    22.  

    5、在 resources 目录中,创建包: com/project/mapper(必须和接口所在包同名,注意:创建包目录打 “ / ” 而非 “ . ”),在包中导入mapper配置文件。

    namespace为命名空间,必须和 mapper 接口同名

    1. "com.project.mapper.IProductMapper">
    2.    "add">
    3.        insert into t_product(p_name,p_createDate,p_price)
    4.        values(#{name},#{createDate},#{price});
    5.    

    6、建立 service 父类 BaseService

    1. public class BaseService {
    2.    private static SqlSessionFactory factory;
    3.    static {
    4.        try {
    5.            //从类路径中,加载主配置文件
    6.            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
    7.            //创建会话工厂
    8.            factory = new SqlSessionFactoryBuilder().build(r);
    9.       } catch (IOException e) {
    10.            e.printStackTrace();
    11.       }
    12.   }
    13.    /**
    14.     * 创建并返回sqlsession对象
    15.     * @return sqlsession对象
    16.     */
    17.    public SqlSession getSession(){
    18.        return factory.openSession();
    19.   }
    20. }

    7、建立 service 接口实现类

    1. public class ProductServiceImpl extends BaseService implements IProductService {
    2.    @Override
    3.    public void add(ProductBean productBean) {
    4.        //创建并得到会话对象
    5.        SqlSession session = this.getSession();
    6.        //创建并返回mapper接口对象
    7.        IProductMapper mapper = session.getMapper(IProductMapper.class);
    8.        mapper.add(productBean);
    9.        //提交事务
    10.        session.commit();
    11.        //关闭连接
    12.        session.close();
    13.   }
    14. }

    在开发中,有时候需要得到新加记录的编号,由于编号很多时候是自动增长列,有DBMS 进行分配。所有,新加记录的编号,开发者是不清楚的。这时,可以在语句块中添加属性 useCenerateKeys,允许得到自动增长列的值,KeyPropertry 表示将自动增长列的值,填充实体对象的哪个属性

    1. "addProduct" useGeneratedKeys="true" keyProperty="id">
    2.    insert into t_product(p_name,p_createDate,p_price)
    3.    values (#{name},#{createDate},#{price})

    删除:

    1、在 mapper 语句中,加入删除语句块

    1. "del">
    2.    delete from t_product where pk_productId=#{id};

    如果方法中,只有一个参数,并且该参数是简单类型(int、String),占位符名称可以随意

    2、书写 service 方法

    1. public void del(Integer id) {
    2.    SqlSession session = this.getSession();
    3.    IProductMapper mapper = session.getMapper(IProductMapper.class);
    4.    mapper.del(id);
    5.    session.commit();
    6.    session.close();
    7. }

    修改:

    1、如果 mapper 方法中,有多个参数,必须给参数加上别名

    public void update(@Param("pid") Integer id,@Param("price") Integer price);

    2、在 mapper 语句中,加入修改语句块

    1. "update">
    2.    update t_product set p_price=#{price} where pk_productId=#{pid};

    3、书写业务方法

    1. public void update( Integer id, Integer price) {
    2.    SqlSession session = this.getSession();
    3.    IProductMapper mapper = session.getMapper(IProductMapper.class);
    4.    mapper.update(id,price);
    5.    session.commit();
    6.    session.close();
    7. }

    mybatis 查询操作

    在执行查询操作时,需要指定查询操作返回的结果。可以通过 resultType 和 resultMap 指定义。

    resultType 用于指定返回的实体类型。可以是简单类型(int,String),可以是对象类型。 当返回的是实体类型时,要求属性名和列名一致。否则无法根据列名封装对象的属性。

    resultMap 用于定义属性和数据库列的对应关系,提高重用性,其他查询语句也可以引用。当列名和属性同名时可以不用写映射。


    查询所有:

    1、在 mapper 文件中定义resultMap 映射

    1. "productMap" type="productBean">
    2.    "pk_productId" property="id">
    3.    "p_name" property="name">
    4.    "p_createDate" property="createDate">
    5.    "p_price" property="price">

    2、在 mapper 文件中书写查询语句块

    3、书写业务方法

    1. public List findAll() {
    2.    SqlSession session = this.getSession();
    3.    IProductMapper mapper = session.getMapper(IProductMapper.class);
    4.    List list = mapper.findAll();
    5.    session.close();
    6.    return list;
    7. }

    条件查询:

    条件查询时,mabatis有两种占位符 $和#、

    #在生成 SQL 时,对应字符类型、日期类型参数,会拼装引号。

    $在生成 SQL 时,不会拼装引号,可用于 order by 之类的参数拼装,使用$时容易引起 SQL 注入。

    按姓名模糊查询

    1、在 mapper 文件中,书写 SQL

    2、书写业务方法

    1. public List findByName(String name) {
    2.    SqlSession session = this.getSession();
    3.    IProductMapper mapper = session.getMapper(IProductMapper.class);
    4.    List list = mapper.findByName(name);
    5.    session.close();
    6.    return list;
    7. }

    动态条件分页查询

    1、建立业务接口方法

    1. public CutPageBean cutByItem(int pageNO,String name,
    2. LocalDate startDate, LocalDate endDate);

    2、建立 Mapper 接口方法

    1. /**
    2. * 分页查询当前页数据
    3. * @param name 商品名
    4. * @param startDate 生产起始日期
    5. * @param endDate 生产结束日期
    6. * @param startRow 起始记录数
    7. * @param pageSize 查询条数
    8. * @return 商品集合
    9. */
    10. public List cutList(@Param("name") String name,
    11.                                 @Param("startDate") LocalDate startDate,
    12.                                 @Param("endDate") LocalDate endDate,
    13.                                 @Param("startRow") Integer startRow,
    14.                                 @Param("pageSize") Integer pageSize);
    15. /**
    16. * 分页统计总记录数
    17. * @param name 商品名
    18. * @param startDate 生产开始日期
    19. * @param endDate 生产结束日期
    20. * @return 总记录数
    21. */
    22. public int cutCount(@Param("name") String name,
    23.                    @Param("startDate") LocalDate startDate,
    24.                    @Param("endDate") LocalDate endDate);

    3、在 Mapper 文件中,书写 SQL 语句 如果一段 SQL 语句可以用于多个语句块时,可以用标签独立出来,便于重用

    1. "dynaSql">
    2.    <if test="name != null and name != '' ">
    3.        and p_name like "%"#{name}"%"
    4.    if>
    5.    <if test="startDate != null">
    6.        and p_createDate >= #{createDate}
    7.    if>
    8.    <if test="endDate != null">
    9.        
    10.        and p_createDate <= #{endDate}
    11.       ]]>
    12.    if>

    if 标题条件为真时,表示拼接指定的 SQL 语句。由于在 XML 文件中有一些特殊字符,比如:>、<、&等,这时可以用  包起来。这样无论里面是什么值都当字符串处理,不会因为有特殊符号,而导致编译报错。

    引入语句块,采用标签

    4、书写业务方法

    1. @Override
    2. public CutPageBean cutByItem(int pageNO, String name,
    3. LocalDate startDate, LocalDate endDate) {
    4.    SqlSession session = this.getSession();
    5.    IProductMapper mapper = session.getMapper(IProductMapper.class);
    6.    CutPageBean cutBean = new CutPageBean<>();
    7.    cutBean.setList(mapper.cutList(name,startDate,endDate,
    8. (pageNO-1)*cutBean.PAGESIZE,cutBean.PAGESIZE));
    9.    cutBean.setCount(mapper.cutCount(name,startDate,endDate));
    10.    return cutBean;
    11. }

    mybatis 注解

    使用 mybatis 注解开发,可以在定义 mapper 接口时书写 SQL 语句。可以省去类配置文件,简洁方便。但是比较复杂的 SQL 和动态 SQL 还是建议书写配置类文件。

  • 相关阅读:
    Ubuntu下安装、运行Nginx
    记录使用iText7查找PDF内容关键字坐标,加盖电子签名、印章
    宝塔:如何开启面板ssl并更新过期ssl
    如何从命令行运行3dMax脚本(MAXScript或Python)?
    构建精致 Chrome 插件:开箱即用的 TypeScript 模板 | 开源日报 No.51
    【RocketMQ】(八)Rebalance负载均衡
    go 适配器模式
    使用webpack-bundle-analyzer分析uni-app 的微信小程序包大小(HbuilderX运行)
    目标检测论文解读复现之二:基于改进YOLOv5的轻量化航空目标检测方法
    力扣 -- 215. 数组中的第K个最大元素
  • 原文地址:https://blog.csdn.net/weixin_66564094/article/details/126695237