springboot 整合 mybatis

整合 mybatis

第一步,选择 mybatis 和 springboot 的整合依赖

勾选上后 spring boot 会自动生成对应的 dependence,若没有勾选,也可以在 pom.xml 文件中手动输入对应的 mabatis 整合依赖,以及 mysql Driver 依赖

第二步:在 yml 配置文件中配置数据库资源

XML 复制代码
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/learbase
    username: root
    password: 1234

第三步:编写sql并运行

封装类:

java 复制代码
package com.example.springmabatis.Pojo;

public class User {

    private String username;
    private String password;
    private int id;

    public User() {
    }

    public User(String username, String password, int id) {
        this.username = username;
        this.password = password;
        this.id = id;
    }

    /**
     * 获取
     * @return username
     */
    public String getUsername() {
        return username;
    }

    /**
     * 设置
     * @param username
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * 获取
     * @return password
     */
    public String getPassword() {
        return password;
    }

    /**
     * 设置
     * @param password
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 获取
     * @return id
     */
    public int getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(int id) {
        this.id = id;
    }

    public String toString() {
        return "User{username = " + username + ", password = " + password + ", id = " + id + "}";
    }
}

接口:

java 复制代码
package com.example.springmabatis.dao;

import com.example.springmabatis.Pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserDao {

    @Select("select * from t_user where id = #{id}")
    public User getById(int id) ;

}

第一次运行,报错:

org.mybatis.spring.MyBatisSystemException

检查后发现,是 yml 配置文件中的数据库信息错误

将 learnbase 写成了 learbase

修改后运行成功

相关推荐
qo_tn16 小时前
微信机器人-webhook技术文档_04-Docker-Compose部署与生产化配置
后端
程序员cxuan16 小时前
Claude Opus 5 的系统提示词被扒出来了
人工智能·后端·程序员
董员外16 小时前
RAG 系统进化论(十):可运营 RAG,从原型到长期运行的知识系统
人工智能·后端·设计模式
newerp16 小时前
贪心算法 — 局部最优推导全局最优
后端
凤山老林16 小时前
可观测性落地:Spring Boot 3.x + Actuator + Prometheus + Grafana 监控体系搭建
spring boot·grafana·prometheus
掘金者阿豪16 小时前
SQL Server数据迁移实践:KES V9R4C019如何解决兼容性、性能与运维挑战
后端
不爱说话郭德纲16 小时前
零基础,学做KMP项目,TRAE Work手把手带你月薪.....
前端·后端·app
鹏北海17 小时前
AI 全栈时代的多语言 SDK 版本管理:认识 mise
前端·后端
未秃头的程序猿17 小时前
凌晨3点被叫醒:线上OOM,我用这套流程40分钟定位根因
java·jvm·后端
用户2986985301417 小时前
HTML 转 Word 指南:新手入门教程
人工智能·后端·python