SpringBootはアノテーションを使用してMyBatisを統合します

1.データの準備

データベースを作成する

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'、 'Introduction to Spring Boot Basics'、 'エントリから熟練した説明へ...');
INSERT INTO` t_article` VALUES( '2'、 'Introduction to Spring Cloud Basics'、 '初心者から熟練した説明まで...');

コードをコピーする

テーブル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'、 'Very complete and detail'、 '
Running snail'、 '1'); INSERT INTO` t_comment` VALUES( '2'、 'Like one'、 'tom'、 '1 ');
INSERT INTO `t_comment` VALUES(' 3 '、' very detail '、' kitty '、' 1 ');
INSERT INTO` t_comment` VALUES(' 4 '、' very good、very detail '、' Zhang San '、' 1 ');
INSERT INTO `t_comment` VALUES(' 5 '、' Very good '、' Zhang Yang '、' 2 ');

コードをコピーする

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>

コードをコピーする

エンティティクラスの記述記事とコメント

コードをコピーする

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);

}

コードをコピーする

4、テスト

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

}

コードをコピーする


#Openキャメルケース名マッチングマッピングmybatis.configuration.map-underscore-to-camel-case = true

 

 *キャメルケースの命名方法は、エンティティクラスCommentでt_commentテーブルのa_idフィールドをaId属性として設計するために使用されるため、結果に正しくマップできません。キャメルケース名の一致マッピングルールがオンになると、クエリされたすべてのt_commentテーブルデータが対応するCommentエンティティクラスオブジェクトに正常にマッピングされます。

 * MyBatisインターフェースファイルに@Mapperアノテーションを追加する必要があります。Mapperインターフェースの記述が多すぎる場合は、プロジェクト起動クラスに@MapperScan( "XXX")アノテーションを追加できます[必要な特定のパッケージ名を指定する必要がありますスキャン] 1つずつ回避する@Mapperアノテーションの追加による問題

 * @Mapperアノテーションを追加した後、このインターフェイスはコンパイル時に対応する実装クラスを生成します。同じIDが生成されるため、このインターフェイスで同じ名前のメソッドを定義できないことに注意してください。これは、インターフェイスはreContainedをサポートしていません


*複数のパラメーターの場合、各パラメーターに@Paramアノテーションを付ける必要があります。そうしないと、対応するパラメーターが見つからず、エラーが報告され     
    ます。publicUser login(@Param( "name")String name、@ Param( "pwd)")文字列pwd);

カテゴリ: スプリングブーツ

おすすめ

転載: blog.csdn.net/suixinsuoyu12519/article/details/112980343