首页 > 其他分享 >SpringBoot 整合 MyBatis

SpringBoot 整合 MyBatis

时间:2022-10-03 15:34:18浏览次数:81  
标签:SpringBoot xxx private 整合 mysql MyBatis import com String

本文基于:https://www.bilibili.com/video/BV15b4y1a7yG?p=28&vd_source=cf8900ba33d057d422c588abe5d5290d

pom.xml 中导入坐标

<dependencies>
  ...
  <!-- 引入MyBatis -->
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
  </dependency>

  <!-- 导入数据库的jar包 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>

这里使用的数据库是 MySql

配置 application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3309/FruitDatabase
    username: root
    password: 123456

上面的代码够语义化了,就不解释了

新建实体类

延续之前的例子,建立一个 Fruit

package com.example.xxx.entity;

public class Fruit {
    private String fruitId;
    private String fruitName;
    private String avatar;
    private Double price;
    private Integer stock;

    // Getter&Setter
    // toString
}

新建 Dao 接口

package com.example.xxx.dao;

import xxx...;

@Mapper
public interface FruitDao {
    @Select("select * from fruit_table where fruit_id = #{id}")
    public Fruit getById(String id);
}

去测试类中测试一下

// TestClass
package com.example.xxx;

import com.example.xxx.dao.FruitDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class TestClass {

    @Autowired
    private FruitDao fruitDao;

    @Test
    void contextLoads() {
        System.out.println(fruitDao.getById("1"));
    }
}

运行 contextLoads 方法:

xxx
Fruit{fruitId='null', fruitName='null', avatar='http://www.xxx.com/pears.jpg', price=74.2, stock=80}
xxx

成功读取到了数据库中的信息,不过这里的 fruitIdfruitNamenull 是由于我们配置实体类的字段名与数据库中的字段名不匹配,数据库中的字段是 fruit_id 这种形式,而 JAVA 实体类中使用的是 小驼峰,后续的博客应该会提到相关的内容

标签:SpringBoot,xxx,private,整合,mysql,MyBatis,import,com,String
From: https://www.cnblogs.com/hhsk/p/16750587.html

相关文章