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

介紹

MyBatis 是一款優(yōu)秀的、開源的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡單的 XML 或注解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數(shù)據(jù)庫中的記錄。

??這就表明,MyBatis是SQL映射框架(SQL mapping framework),和Hibernate工作原理并不相同,因?yàn)镠ibernate是ORM 框架。
??MyBatis社區(qū)已經(jīng)為Spring Boot提供了starter依賴,因?yàn)槲覀兛梢栽赟pring Boot中愉快地使用MyBatis.
??本次介紹將不使用MyBatis XML來執(zhí)行數(shù)據(jù)庫查詢,而是使用基于注釋的mappers(annotation-based mappers).

準(zhǔn)備工作

??因?yàn)楸敬窝菔镜氖侨绾卧赟pring Boot中使用MyBatis操作MySQL,進(jìn)行數(shù)據(jù)庫的增刪改查。所以,我們需要對MySQL數(shù)據(jù)庫做一些準(zhǔn)備工作。具體說來,就說在MySQL的test數(shù)據(jù)庫下新建表格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/ 中創(chuàng)建Spring Boot項(xiàng)目,加入Web, MyBatis, MySQL起始依賴,如下圖:

項(xiàng)目創(chuàng)建

項(xiàng)目結(jié)構(gòu)

??整個項(xiàng)目的結(jié)構(gòu)如下圖:

項(xiàng)目結(jié)構(gòu)

??畫紅線的框內(nèi)的文件是我們需要新增或修改的文件。
??先是實(shí)體類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 受影響的行數(shù)
     */
    @Update("update person set name=#{name},age=#{age},city=#{city} where id=#{id}")
    Integer update(Person person);

    /**
     * 刪除操作
     * @param id
     * @return 受影響的行數(shù)
     */
    @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();

    /**
     * 根據(jù)主鍵查詢單個
     * @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<Person> selectAll() {
        return personMapper.selectAll();
    }

}

??最后一步是整個項(xiàng)目的配置文件application.properies,主要是MySQL數(shù)據(jù)庫的連接設(shè)置,其代碼如下:

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

??整個項(xiàng)目的結(jié)構(gòu)及代碼介紹完畢。

運(yùn)行及測試

??啟動Spring Boot項(xiàng)目,在瀏覽器中輸入: 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 即可查詢所有的記錄。
??本次分享到此結(jié)束,接下來還會繼續(xù)分享更多的關(guān)于Spring Boot的內(nèi)容,歡迎大家交流~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容