美文网首页
使用MyBatis框架搭建ORM映射

使用MyBatis框架搭建ORM映射

作者: 肖sir_嘉立老师 | 来源:发表于2019-11-21 23:30 被阅读0次

一、框架介绍

MyBatis是一个基于Java的持久层框架。其本是apache的一个名为iBatis的开源项目, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)。

最新版本是MyBatis 3.5.3 ,其发布时间是2019年10月20日。

MyBatis的主要功能:

  • 它支持定制化 SQL、存储过程以及高级映射。
  • MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。
  • MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Ordinary Java Objects,普通的 Java对象)映射成数据库中的记录。

MyBatis的整体架构:

MyBatis的整体架构-转载自鸟哥.png

知识拓展:
持久(Persistence),即把数据(如内存中的对象)保存到可永久保存的存储设备中(如磁盘)。
持久化的主要应用是将内存中的数据存储在关系型的数据库中,当然也可以存储在磁盘文件中、XML数据文件中等等。
持久层(Persistence Layer),即专注于实现数据持久化应用领域的某个特定系统的一个逻辑层面,将数据使用者和数据实体相关联。
对象关系映射(Object Relational Mapping,简称ORM)是通过使用描述对象和数据库之间映射的元数据,将面向对象语言程序中的对象自动持久化到关系数据库中。
因此,ORM的作用就是在关系型数据库和对象之间作一个映射,使得我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作

二、MyBatis调用的一般步骤

  1. 配置mybatis-config.xml 全局的配置文件 (1、数据源,2、外部的mapper)
  2. 创建SqlSessionFactory
  3. 通过SqlSessionFactory创建SqlSession对象
  4. 通过SqlSession操作数据库 CRUD
  5. 调用session.commit()提交事务
  6. 调用session.close()关闭会话

三、SpringBoot中应用MyBatis

1.引入MyBatis的依赖

<!-- 数据库使用MySQL,所以需要引入MySQL的驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!-- MyBatis是基于JDBC基础上上二次封装的,因此依赖于JDBC -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!--引入包含MyBatis依赖的starter,把默认配置都设定好-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

2.项目配置文件:MyBatis框架的参数配置

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
mybatis.mapper-locations: classpath:mapper/*.xml

3.创建MySQL数据表

CREATE TABLE `t_customer` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

4.创建实体类Customer

package com.zhbit.domain;

import org.springframework.stereotype.Component;
 
/**
 * @Author:xiao sir
 * @Date: 2019/11/21
 * @Time: 13:56
 */
@Component
public class Customer {
    private Integer id;
    private String name;
    private String realName;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getRealName() {
        return realName;
    }
 
    public void setRealName(String realName) {
        this.realName = realName;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name+ '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }
}

5.创建CustomerController控制器

在与前端页面商量好,确定好后端需要提供什么功能后,根据RESTful的规则,双方列出HTTP通信的请求路径以及请求参数明细。从而明确CustomerController需要提供哪些功能。

package com.zhbit.controller;
 
import com.zhbit.domain.Customer;
import com.zhibt.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @Author:xiao sir
 * @Date: 2019/11/21 
 * @Time: 14:22
 */
 
@RestController
@RequestMapping("/customer")
public class CustomerController {
 
    @Autowired
    private ICustomerService customerService;

    @Autowired
    private Customer customer;

    //显示顾客
    @RequestMapping("get")
    public List<Customer> getCustomer() throws Exception {
        return customerService.getCustomer();
    }
    //删除顾客
    @RequestMapping("delete/{id}")
    public String deleteCustomer(@PathVariable int id) throws Exception {
        customerService.deleteCustomer(id);
        return "你已经删掉了id为"+id+"的顾客";
    }
    //增加顾客
    @RequestMapping("add")
    public String addCustomer() throws Exception {
        customer.setuserName("阿花");
        customer.setrealName("荷花");
        customerService.addCustomer(customer);
        return "增加顾客";
    }
}

6.业务逻辑接口ICustomerService

package com.zhbit.iservice;
import com.zhbit.domain.Customer;

import java.util.List;

public interface  ICustomerService {

    //显示所有客户
    public List<Customer> getCustomer() throws Exception;
    //根据id删除客户
    public void deleteCustomer(int id) throws Exception;
    //新增客户
    public void addCustomer(Customer customer) throws Exception;

}

7.实现业务逻辑CustomerServiceImp

package com.zhbit.serviceImp

import com.zhbit.dao.CustomerMapper;
import com.zhbit.domain.Customer;
import com.zhbit.iservice.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerServiceImpl implements ICustomerService {

    @Autowired
    private CustomerMapper customerMapper;


    @Override
    public List<Customer> getCustomer() throws Exception {
        return customerMapper.getCustomer();
    }

    @Override
    public void deleteCustomer(int id) throws Exception {
        customerMapper.deleteCustomer(id);
    }

    @Override
    public void addCustomer(Customer customer) throws Exception {
        customerMapper.addCustomer(customer);
    }
}

8.DAL数据访问层CustomerMapper

由于使用了ORM框架,原来dao层中需要使用JDBC实现的数据库访问,都通过MyBatis框架实现映射。因此,只需根据数据表的结构及类型,创建一个与数据库表一一对应的Mapper类,并通过一个同名的xml文件配置到MyBatis框架中,框架自动实现数据映射。

package com.zhbit.dao;

import com.zhbit.domain.Customer;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface CustomerMapper {

    //获取用户名单
    public List<Customer> getCustomer() throws Exception;
    //根据id删除用户
    public void deleteCustomer(int id)throws Exception;
    //新增用户
    public void addCustomer(Customer customer)throws Exception;

}

(对应的CustomerMapper.xml)

<?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.zhbit.mapper.CustomerMapper">
 
    <resultMap id="BaseResultMap" type="com.zhbit.domain.Customer">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="realName" jdbcType="VARCHAR" property="realName" />
    </resultMap>
 
    <select id="getCustomer" resultType="com.zbhit.domain.Customer">
        select * from t_customer
    </select>
    <delete id="deleteCustomer" parameterType="Integer">
        delete from t_customer where id =#{id}
    </delete>
    <insert id="addCustomer" parameterType="com.zhbit.domain.Customer">
        insert into t_customer(id,name,realName)values(#{id},#{name},#{realName})
    </insert>
</mapper>

注意:所有的Mapper文件都放在静态资源resources下的mapping文件夹中。

8.项目启动文件:加入扫描所有mapping文件的注解

package com.zhbit;
 
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@MapperScan("com.zhbit.mapper") //扫描的mapper
@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

建议:把启动文件移到com.zhbit命名空间下。

参考文献

  1. MyBatis官方文档
  2. MyBatis教程

相关文章

  • 使用MyBatis框架搭建ORM映射

    一、框架介绍 MyBatis是一个基于Java的持久层框架。其本是apache的一个名为iBatis的开源项目, ...

  • mybatis笔记

    MyBatis框架 1.ORM框架介绍 1.1 什么是ORM? 对象关系映射(Object Relational ...

  • 浅尝ORM

    ORM(Object relation Mapping)对象关系映射 在使用MyBatis框架时,可以将Java对...

  • ORM

    在主流 ORM 框架(Hibernate、Mybatis)的文章。 1. ORM 1.1 What 对象关系映射(...

  • 4.Mybatis

    简介 Mybatis是一个ORM框架,ORM(Object relational Mapping)是对象关系映射模...

  • 编程改变世界(6)-- mybatis入门学习

    mybatis是一个ORM(Object Relational Mapping)框架,即对象关系映射框架。 简单...

  • Spring整合Mybatis

    一 、 Mybatis概览 说到mybatis就不得不说ORM框架,即对象-关系映射(Object-Relatio...

  • 今日课题——如何理解MyBatis(优点&缺点)&MyBatis

    一、MyBatis篇 1、什么是MyBatis (1)Mybatis是一个半ORM(对象关系映射)框架,它内部封装...

  • 2020最新版-Mybaits面试题

    MyBatis简介 MyBatis是什么? MyBatis 是一款优秀的持久层框架,一个半 ORM(对象关系映射)...

  • Mybatis面试题整理

    1、什么是Mybatis? 1、Mybatis 是一个半 ORM( 对象关系映射)框架,它内部封装了 JDBC,开...

网友评论

      本文标题:使用MyBatis框架搭建ORM映射

      本文链接:https://www.haomeiwen.com/subject/hruxwctx.html