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;
    }
}
Comment
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;
    }
}
Article

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() {
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM