Spring Boot使用注解方式整合MyBatis

一、数据准备

创建数据库

CREATE DATABASE springbootdata DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

创建表t_article并插入相关数据

复制代码

CREATE TABLE `t_article` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
  `title` varchar(200) DEFAULT NULL COMMENT '文章标题',
  `content` longtext COMMENT '文章内容',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');

复制代码

创建表t_comment并插入相关数据

复制代码

  CREATE TABLE `t_comment` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
  `content` longtext COMMENT '评论内容',
  `author` varchar(200) DEFAULT NULL COMMENT '评论作者',
  `a_id` int(20) DEFAULT NULL COMMENT '关联的文章id',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');

复制代码

二、创建项目

整体项目结构

引入MySQL和MyBatis依赖启动器

复制代码

    
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.13</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

复制代码

编写实体类Article和Comment

复制代码

package com.uos.databases.domain;

/**
 * 评论实体类
 */
public class Comment {
    private Integer id;
    private String content;
    private String author;
    private Integer aId;

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }
}

复制代码

复制代码

package com.uos.databases.domain;

import java.util.List;

/**
 * 文章类
 */
public class Article {
    private Integer id;
    private String title;
    private String content;
    private List<Comment> commentList;

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", commentList=" + commentList +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<Comment> getCommentList() {
        return commentList;
    }

    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }
}

复制代码

application.yml

复制代码

spring:
  datasource:
    url: jdbc:mysql://192.168.41.132:3306/springbootdata?serverTimezone=UTC
    username: root
    password: 1
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 20
      min-idle: 10
      max-active: 100
      driver: com.mysql.jdbc.Driver

复制代码

配置类DataSourceConfig

复制代码

package com.uos.databases.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;

@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource getDruid(){
        return new DruidDataSource();
    }
}

复制代码

三、使用注解方式整合MyBatis

ArticleMapper类

复制代码

package com.uos.databases.mapper;


import com.uos.databases.domain.Article;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;


@Mapper
public interface ArticleMapper {
    @Select("SELECT * FROM t_article WHERE id =#{id}")
    public Article selectArticle(Integer id);

    public int updateArticle(Article article);

}

复制代码

CommentMapper类

复制代码

package com.uos.databases.mapper;


import com.uos.databases.domain.Comment;
import org.apache.ibatis.annotations.*;


@Mapper
public interface CommentMapper {
    @Select("SELECT * FROM t_comment WHERE id =#{id}")
    public Comment findById(Integer id);

    @Insert("INSERT INTO t_comment(content,author,a_id) " +
            "values (#{content},#{author},#{aId})")
    public int insertComment(Comment comment);

    @Update("UPDATE t_comment SET content=#{content} WHERE id=#{id}")
    public int updateComment(Comment comment);

    @Delete("DELETE FROM t_comment WHERE id=#{id}")
    public int deleteComment(Integer id);

}

复制代码

四、测试

MybatisApplicationTests测试类

复制代码

@SpringBootTest
class MybatisApplicationTests {

    @Autowired
    private CommentMapper commentMapper;

    @Test
    public void selectComment() {
        Comment comment = commentMapper.findById(2);
        System.out.println(comment);
    }

    @Autowired
    private ArticleMapper articleMapper;

    @Test
    public void selectArticle() {
        Article article = articleMapper.selectArticle(2);
        System.out.println(article);
    }


    @Test
    void contextLoads() {
    }

}

复制代码

#开启驼峰命名匹配映射
mybatis.configuration.map-underscore-to-camel-case=true

 * 实体类Comment中使用了驼峰命名方式将t_comment表中的a_id字段设计成了aId属性,所以无法正确映射到结果。开启驼峰命名匹配映射规则后,查询的t_comment表数据全部成功映射到与之对应的Comment实体类对象中。

 * 在MyBatis接口文件中需要添加@Mapper注解,如果编写的Mapper接口过多时,可以在项目启动类上添加@MapperScan("XXX")注解【需要指定需要扫描的具体包名】,以此避免逐个添加@Mapper注解带来的麻烦

 * 添加了@Mapper注解之后这个接口在编译时会生成相应的实现类 , 需要注意的是:这个接口中不可以定义同名的方法,因为会生成相同的id, 也就是说这个接口是不支持重载的


* 对于多个参数来说,每个参数之前都要加上@Param注解, 要不然会找不到对应的参数进而报错     
    public User login(@Param("name")String name, @Param("pwd")String pwd);

分类: Spring Boot

猜你喜欢

转载自blog.csdn.net/suixinsuoyu12519/article/details/112980343