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).java

准备工做

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

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起始依赖,以下图:web

项目建立

项目结构

  整个项目的结构以下图:spring

项目结构

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

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<Person> selectAll();

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

}

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

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<Person> 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

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

运行及测试

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

插入记录

  在浏览器中输入: 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的内容,欢迎你们交流~~

相关文章
相关标签/搜索