SpringBoot项目如何引进MyBatis ?如何使用及操作数据库

一、创建SpringBoot项目,导入依赖

首先需要创建一个SpringBoot项目,然后再pom.xml文件中,右击选择”Generate“,依次进行下述操作:(同样也可以在项目创建的时候选择MyBatis Framework 和 MySQL Driver)

然后再次拉取即可。或者可以直接导入依赖:

<!--Mybatis 依赖包-->
<dependency>
 <groupId>org.mybatis.spring.boot</groupId>
 <artifactId>mybatis-spring-boot-starter</artifactId>
 <version>3.0.3</version>
</dependency>
<!--mysql驱动包-->
<dependency>
 <groupId>com.mysql</groupId>
 <artifactId>mysql-connector-j</artifactId>
 <scope>runtime</scope>
</dependency>

二、配置数据库连接字符串

MyBatis中要连接数据库,需要数据库相关参数配置:MySQL驱动类,登录名,密码,数据库连接字符串。(properties文件和yml文件可以通过网上对这两种文件的在线转换器来转换使用)
propert文件:
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?
characterEncoding=utf8&useSSL=false
#连接数据库的⽤⼾名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=root

yml文件

# 数据库连接配置
spring:
 datasource:
  url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
  username: root
  password: '123456'
  driver-class-name: com.mysql.cj.jdbc.Driver
如果使用 MySQL 是 5.x 之前的,使用的是"com.mysql.jdbc.Driver",如果是大于 5.x 使用的
是“com.mysql.cj.jdbc.Driver。
如果无密码或者密码为纯数字,就需要加上单引号,别的不需要。

三、创建数据库表

此处我使用的是Navicat连接数据库之后插入sql代码,别的客户端也可以。

-- 创建数据库
DROP DATABASE IF EXISTS mybatis_test;

CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;

-- 使用数据数据
USE mybatis_test;

-- 创建表[用户表]
DROP TABLE IF EXISTS userinfo;
CREATE TABLE `userinfo` (
        `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
        `username` VARCHAR ( 127 ) NOT NULL,
        `password` VARCHAR ( 127 ) NOT NULL,
        `age` TINYINT ( 4 ) NOT NULL,
        `gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-女 0-默认',
        `phone` VARCHAR ( 15 ) DEFAULT NULL,
        `delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
        `create_time` DATETIME DEFAULT now(),
        `update_time` DATETIME DEFAULT now(),
        PRIMARY KEY ( `id` ) 
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4; 

-- 添加用户信息
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'admin', 'admin', 18, 1, '18612340001' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );


-- 创建文章表
DROP TABLE IF EXISTS articleinfo;
        
CREATE TABLE articleinfo (
        id INT PRIMARY KEY auto_increment,
        title VARCHAR ( 100 ) NOT NULL,
        content TEXT NOT NULL,
        uid INT NOT NULL,
        delete_flag TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
        create_time DATETIME DEFAULT now(),
        update_time DATETIME DEFAULT now() 
) DEFAULT charset 'utf8mb4';

-- 插入测试数据
INSERT INTO articleinfo ( title, content, uid ) VALUES ( 'Java', 'Java正文', 1 );

四、编写代码

UserInfo:
package com.example.mybatis_demo.model;

import lombok.Data;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 
 * Date: 2024-07-25
 * Time: 21:06
 */

@Data
public class UserInfo {

    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private Integer gender;
    private String phone;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
}
UserService:
package com.example.mybatis_demo.service;

import com.example.mybatis_demo.mapper.UserInfoMapper;
import com.example.mybatis_demo.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 
 * Date: 2024-07-25
 * Time: 21:28
 */

@Service
public class UserService {


    @Autowired
    private UserInfoMapper userInfoMapper;

    public List<UserInfo> queryUserInfos(){
        return  userInfoMapper.queryUserInfos();
    }
}
UserInfoMapper:       
package com.example.mybatis_demo.mapper;

import com.example.mybatis_demo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 
 * Date: 2024-07-25
 * Time: 21:18
 */

@Mapper
public interface UserInfoMapper {

    @Select("select * from userinfo")
    List<UserInfo> queryUserInfos();
}
UserController:
package com.example.mybatis_demo.controller;

import com.example.mybatis_demo.mapper.UserInfoMapper;
import com.example.mybatis_demo.model.UserInfo;
import com.example.mybatis_demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 
 * Date: 2024-07-25
 * Time: 21:22
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/queryUserInfos")
    public List<UserInfo> queryUserInfos(){
        return  userService.queryUserInfos();
    }
}

单元测试代码:

想要测试哪个就在它相应的代码界面右击选择”Generate→Test",然后选择想要测试的方法即可。

package com.example.mybatis_demo.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 
 * Date: 2024-07-25
 * Time: 22:00
 */

@SpringBootTest
class UserInfoMapperTest {

    @Autowired
    private  UserInfoMapper userInfoMapper;


    @Test
    void queryUserInfos() {
        userInfoMapper.queryUserInfos().forEach(System.out::println);
    }
}

运行结果:

 结果显示没有问题,返回了数据。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合MyBatis可以通过以下步骤进行: 1. 添加依赖:在`pom.xml`文件中添加Spring Boot和MyBatis的相关依赖。 ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` 2. 配置数据源:在`application.properties`或`application.yml`文件中配置数据库连接信息。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=username spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建实体类和Mapper接口:创建对应的实体类和Mapper接口,使用注解或XML配置SQL语句。 ```java // 实体类 public class User { private Long id; private String name; // 省略getter和setter方法 } // Mapper接口 @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(Long id); } ``` 4. 编写Service层:编写Service层的业务逻辑代码,调用Mapper接口进行数据操作。 ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserById(Long id) { return userMapper.findById(id); } } ``` 5. 编写Controller层:编写Controller层的接口代码,调用Service层处理业务逻辑。 ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } } ``` 以上就是Spring Boot整合MyBatis的基本步骤。通过以上配置和代码,Spring Boot会自动扫描并注入相关的Bean,实现MyBatis的整合。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值