亲宝软件园·资讯

展开

Spring Boot MyBatis

一只小熊猫呀 人气:0

整合MyBatis

MyBatis 是一款优秀的持久层框架,原名 iBatis ,2010年迁移到 Goole Code 并改名为 MyBatis ,2013年迁移到 GitHub 上。MyBatis 支持定制化 SQL 、存储过程及高级映射。MyBatis 几乎避免了所有的 JDBC 代码手动设置参数以及获取结果集。在传统的 SSM 框架整合中,使用 MyBatis 需要大量的 XML 配置,而在 Spring Boot 中,MyBatis 提供了一套自动化配置方案,可以做到 MyBatis 开箱即用。

1. 创建项目

创建 Spring Boot 项目,添加 MyBatis 依赖、数据库驱动依赖以及数据库连接池依赖,如下:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <!--       排除默认的jackson-databind         -->
    <exclusion>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<!--    引入fastjson依赖    -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.78</version>
</dependency>
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.3.2</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.9</version>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

2. 创表实体类等

CREATE TABLE `book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) DEFAULT NULL,
  `author` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

实体类 Book

public class Book {
    private Integer id;
    private String name;
    private String author;
    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
    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 getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}

数据库连接配置 application.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/weirdo?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root

3. 创建数据库访问层

创建 BookMapper

传送门

@Mapper
public interface BookMapper {
    int addBook(Book book);
    int deleteBookById(Integer id);
    int updateBookById(Book book);
    Book getBookById(Integer id);
    List<Book> getAllBooks();
}

代码解释:

4. 创建 BookMapper.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.sang.mapper.BookMapper">
    <insert id="addBook" parameterType="com.sang.model.Book">
    INSERT INTO book(name,author) VALUES (#{name},#{author})
    </insert>
    <delete id="deleteBookById" parameterType="int">
        DELETE FROM book WHERE id=#{id}
    </delete>
    <update id="updateBookById" parameterType="com.sang.model.Book">
        UPDATE book set name=#{name},author=#{author} WHERE id=#{id}
    </update>
    <select id="getBookById" parameterType="int" resultType="com.sang.model.Book">
        SELECT * FROM book WHERE id=#{id}
    </select>
    <select id="getAllBooks" resultType="com.sang.model.Book">
        SELECT * FROM book
    </select>
</mapper>

代码解释:

5. 创建Service和BookController

@Service
public class BookService {
    @Autowired
    BookMapper bookMapper;
    public int addBook(Book book) {
        return bookMapper.addBook(book);
    }
    public int updateBook(Book book) {
        return bookMapper.updateBookById(book);
    }
    public int deleteBookById(Integer id) {
        return bookMapper.deleteBookById(id);
    }
    public Book getBookById(Integer id) {
        return bookMapper.getBookById(id);
    }
    public List<Book> getAllBooks() {
        return bookMapper.getAllBooks();
    }
}
@RestController
public class BookController {
    @Autowired
    BookService bookService;
    @GetMapping("/bookOps")
    public void bookOps() {
        Book b1 = new Book();
        b1.setName("西厢记");
        b1.setAuthor("王实甫");
        int i = bookService.addBook(b1);
        System.out.println("addBook>>>" + i);
        Book b2 = new Book();
        b2.setId(1);
        b2.setName("朝花夕拾");
        b2.setAuthor("鲁迅");
        int updateBook = bookService.updateBook(b2);
        System.out.println("updateBook>>>"+ JSON.toJSONString(updateBook));
        Book b3 = bookService.getBookById(1);
        System.out.println("getBookById>>>"+JSON.toJSONString(b3));
        int delete = bookService.deleteBookById(2);
        System.out.println("deleteBookById>>>"+ JSON.toJSONString(delete));
        List<Book> allBooks = bookService.getAllBooks();
        System.out.println("getAllBooks>>>"+JSON.toJSONString(allBooks));
    }
}

6. 配置 pom.xml 文件

在 Maven 工程中,XML 配置文件建议写在 resources 目录下,但是上文的 Mapper.xml 文件写在包下,Maven 在运行时会忽略包下的 XML 文件,因此需要在 pom.xml 文件中重新指明资源文件位置,配置如下:

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
    <resource>
      <directory>src/main/resources</directory>
    </resource>
  </resources>
</build>

在浏览器中数据 http://localhost:8081/bookOps 查看日志:

addBook>>>1
updateBook>>>1
getBookById>>>{"author":"鲁迅","id":1,"name":"朝花夕拾"}
deleteBookById>>>0
getAllBooks>>>[{"author":"鲁迅","id":1,"name":"朝花夕拾"},{"author":"王实甫","id":3,"name":"西厢记"},{"author":"王实甫","id":4,"name":"西厢记"}]

加载全部内容

相关教程
猜你喜欢
用户评论