Spring Boot入门(7)使用MyBatis操作MySQL

介绍

MyBatis 是一款优秀的、开源的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

  这就表明,MyBatis是SQL映射框架(SQL mapping framework),和Hibernate工作原理并不相同,因为Hibernate是ORM 框架。
  MyBatis社区已经为Spring Boot提供了starter依赖,因为我们可以在Spring Boot中愉快地使用MyBatis.
  本次介绍将不使用MyBatis XML来执行数据库查询,而是使用基于注释的mappers(annotation-based mappers).

准备工作

  因为本次演示的是如何在Spring Boot中使用MyBatis操作MySQL,进行数据库的增删改查。所以,我们需要对MySQL数据库做一些准备工作。具体说来,就说在MySQL的test数据库下新建表格person,其中的字段为id,name,age,city,id为自增长的主键。

use test

create table person(
id int primary key auto_increment,
name varchar(20),
age int,
city varchar(20)
);

  接着在 http://start.spring.io/ 中创建Spring Boot项目,加入Web, MyBatis, MySQL起始依赖,如下图:

Spring Boot入门(7)使用MyBatis操作MySQL_第1张图片
项目创建

项目结构

  整个项目的结构如下图:

Spring Boot入门(7)使用MyBatis操作MySQL_第2张图片
项目结构

  画红线的框内的文件是我们需要新增或修改的文件。
  先是实体类Person.java,其代码如下:

package com.hello.MyBatisDemo.domain;

public class Person{

    private Integer id;
    private String name;
    private Integer age;
    private String city;

    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 Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

  接着是基于注释的mappers文件PersonMapper.java,其代码如下:

package com.hello.MyBatisDemo.DAO;

import com.hello.MyBatisDemo.domain.Person;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface PersonMapper {

    /**
     * 添加操作,返回新增元素的 ID
     * @param person
     */
    @Insert("insert into person(id,name,age,city) values(#{id},#{name},#{age},#{city})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insert(Person person);

    /**
     * 更新操作
     * @param person
     * @return 受影响的行数
     */
    @Update("update person set name=#{name},age=#{age},city=#{city} where id=#{id}")
    Integer update(Person person);

    /**
     * 删除操作
     * @param id
     * @return 受影响的行数
     */
    @Delete("delete from person where id=#{id}")
    Integer delete(@Param("id") Integer id);

    /**
     * 查询所有
     * @return
     */
    @Select("select id,name,age,city from person")
    List selectAll();

    /**
     * 根据主键查询单个
     * @param id
     * @return
     */
    @Select("select id,name,age,city from person where id=#{id}")
    Person selectById(@Param("id") Integer id);

}

  下一步是控制文件PersonController.java,其代码如下:

package com.hello.MyBatisDemo.Controller;

import com.hello.MyBatisDemo.DAO.PersonMapper;
import com.hello.MyBatisDemo.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class PersonController {

    @Autowired
    private PersonMapper personMapper;

    @RequestMapping("/insert")
    public String insert(@RequestParam String name,
                         @RequestParam String city,
                         @RequestParam Integer age) {
        Person person = new Person();
        person.setName(name);
        person.setAge(age);
        person.setCity(city);
        personMapper.insert(person);
        return "第"+person.getId()+"条记录插入成功!";
    }

    @RequestMapping("/update")
    public String update(@RequestParam Integer id,
                          @RequestParam String name,
                          @RequestParam String city,
                          @RequestParam Integer age) {
        Person person = new Person();
        person.setId(id);
        person.setName(name);
        person.setAge(age);
        person.setCity(city);
        return personMapper.update(person)+"条记录更新成功!";
    }

    @RequestMapping("/delete")
    public String delete(@RequestParam Integer id) {
        return personMapper.delete(id)+"条记录删除成功!";
    }

    @RequestMapping("/selectById")
    public Person selectById(@RequestParam Integer id) {
        return personMapper.selectById(id);
    }

    @RequestMapping("/selectAll")
    public List selectAll() {
        return personMapper.selectAll();
    }

}

  最后一步是整个项目的配置文件application.properies,主要是MySQL数据库的连接设置,其代码如下:

spring.datasource.url=jdbc:mysql://localhost:33061/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=147369
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

server.port=8100

  整个项目的结构及代码介绍完毕。

运行及测试

  启动Spring Boot项目,在浏览器中输入: http://localhost:8100/insert?name=bob&age=14&city=shanghai 即可插入一条新的记录。如此类似地插入以下三条记录:

Spring Boot入门(7)使用MyBatis操作MySQL_第3张图片
插入记录

  在浏览器中输入: http://localhost:8100/update?id=2&name=tian&age=27&city=shanghai 即可更新id=2的记录
  在浏览器中输入: http://localhost:8100/delete?id=3 即可删除id=3的记录。
  在浏览器中输入: http://localhost:8100/selectById?id=2 即可查询id=2的记录。
  在浏览器中输入: http://localhost:8100/selectAll 即可查询所有的记录。
  本次分享到此结束,接下来还会继续分享更多的关于Spring Boot的内容,欢迎大家交流~~

你可能感兴趣的:(Spring Boot入门(7)使用MyBatis操作MySQL)