1. 程式人生 > 實用技巧 >SpringBoot---基於Mybatis的資料持久層技術

SpringBoot---基於Mybatis的資料持久層技術

整合SpringBoot與Mybatis

1、建立一個Spring Boot專案。pom配置檔案中新增依賴,這裡我們採用了阿里巴巴的Druid連線池

<!-- 阿里巴巴的Druid資料來源依賴啟動器 -->
<
dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.14</version> </dependency>

<!-- Mybatis啟動器 -->
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.2</version> </dependency>

<!-- MySQL資料庫連線驅動 -->
<dependency> <groupId>mysql</groupId> <artifactId
>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>

2、在application.yml 配置檔案中新增相關的資料庫連線配置

# Mysql 資料庫連線配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false&serverTimezone=Asia/Shanghai  #
資料庫埠號/資料庫名?各種引數 username: root password: 123456 # 新增並配置第三方資料來源druid type: com.alibaba.druid.pool.DruidDataSource initialSize: 20 minIdle: 10 maxActive: 100 # 配置MyBatisi的xml配置檔案路徑 mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.zsc.mybatisi.demo1.domain #配置XML對映檔案中指定的實體類別名路徑 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #輸出執行的SQL語句 map-underscore-to-camel-case: true #開啟駝峰命名匹配對映

注意:在配置資料庫的url的時候要在後面加上引數以防亂碼(?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=false)

# serverTimezone=Asia/Shanghai使用上海時區 之前是使用UTC時區,但是插入資料庫會和電腦時間不一樣,少8個小時

3、在資料庫中建立 t_article和t_comment兩張表,並新增一些資料

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基礎入門', '從入門到精通講解...');

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

4、建立表對應的實體類

/**評論實體類*/
@Data
@TableName("t_comment") // 資料庫表名
public class Comment implements Serializable{

  @TableId("id") // 資料庫主鍵欄位
private Integer id;

  @TableField("content") // 資料庫非主鍵欄位
private String content; private String author; private Integer aId;
  
  //@TableField("expire_date")// 資料庫非主鍵欄位
//@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") // 日期格式自動化
  //private Date expireDate;
}
/** 文章實體類 */
@Data
@TableName("t_article") // 資料庫表名
public class Article implements Serializable{

  @TableId("id") // 資料庫主鍵欄位
private Integer id;

  @TableField("title") // 資料庫非主鍵欄位
private String title; private String content; private List<Comment> commentList; }

5、基於註解方式實現對評論的增刪改查,在mapper資料夾中編寫評論的Mapper介面檔案。

@Mapper
public interface CommentMapper {
    //插入評論資料
    @Insert("insert into t_comment(content,author,a_id) "+"values (#{content},#{author},#{aId})")
    int insertComment(Comment comment);

    //刪除
    @Delete("delete from t_comment where id=#{id}")
    int deleteComment(Integer id);

    //查詢
    @Select("select * from t_comment where id=#{id}")
    Comment findById(Integer id);

    //更新
    @Update("update t_comment set content=#{content} shere id=#{id}")
    int updateComment(Comment comment);
}

6、編寫測試方法進行介面方法測試。

@SpringBootTest
@RunWith(SpringRunner.class)
public class CommentMapperTest {
    @Autowired
    CommentMapper commentMapper;

    @org.junit.Test
    public void findById() {
        Comment comment=commentMapper.findById(1);
        System.out.println(comment.toString());
    }
}