【SpringBoot】 整合MyBatis+Postgresql

发布于:2025-07-12 ⋅ 阅读:(14) ⋅ 点赞:(0)

 MyBatis 是一个轻量级的持久化框架,用于简化数据库访问和操作。它通过将 SQL 语句与 Java 代码分离,允许开发者使用 XML 或注解来配置 SQL 语句,并将结果映射为 Java 对象。MyBatis 提供了灵活的 SQL 控制,适合需要精细控制 SQL 的场景,同时支持动态 SQL、存储过程和缓存等功能,以满足不同的需求 。

 整合MyBatis

数据库安装:

【PostgreSQL】安装及使用(Navicat/Arcgis),连接(C#)_postgresql navicat-CSDN博客

数据库连接

下载驱动

由于我电脑上安装的两个版本的Postgresql12和14所以端口得修改

添加表数据

打开编写窗口

以下是mysql数据库的语句

create database if not exists mybatis;

use mybatis;

create table user(
    id int unsigned primary key auto_increment comment 'ID',
    name varchar(100) comment '姓名',
    age tinyint unsigned comment '年龄',
    gender tinyint unsigned comment '性别, 1:男, 2:女',
    phone varchar(11) comment '手机号'
) comment '用户表';

insert into user(id, name, age, gender, phone) VALUES (null,'白眉鹰王',55,'1','18800000000');
insert into user(id, name, age, gender, phone) VALUES (null,'金毛狮王',45,'1','18800000001');
insert into user(id, name, age, gender, phone) VALUES (null,'青翼蝠王',38,'1','18800000002');
insert into user(id, name, age, gender, phone) VALUES (null,'紫衫龙王',42,'2','18800000003');
insert into user(id, name, age, gender, phone) VALUES (null,'光明左使',37,'1','18800000004');
insert into user(id, name, age, gender, phone) VALUES (null,'光明右使',48,'1','18800000005');

以下是postgresql的语句(注意不要建立user表)

-- 1. 创建数据库(兼容IF NOT EXISTS语法需调整)
CREATE DATABASE mybatis;


-- 2. 连接数据库(PostgreSQL无USE命令)
\c mybatis;


-- 3. 创建表(处理自增主键、无符号类型、注释语法)
CREATE TABLE "usertest" (
                        id SERIAL PRIMARY KEY,  -- 自增主键改造
                        name VARCHAR(100),      -- 字符串类型兼容
                        age SMALLINT,           -- TINYINT UNSIGNED → SMALLINT
                        gender SMALLINT,        -- 同age处理逻辑
                        phone VARCHAR(11)       -- 保留原定义
);
COMMENT ON TABLE "usertest" IS '用户表';  -- 表注释单独设置
COMMENT ON COLUMN "usertest".id IS 'ID';
COMMENT ON COLUMN "usertest".name IS '姓名';
COMMENT ON COLUMN "usertest".age IS '年龄';
COMMENT ON COLUMN "usertest".gender IS '性别, 1:男, 2:女';
COMMENT ON COLUMN "usertest".phone IS '手机号';

-- 4. 插入数据(处理自增列、单引号规范)
INSERT INTO "usertest" (name, age, gender, phone) VALUES
                                                  ('白眉鹰王', 55, 1, '18800000000'),  -- 省略自增id [[20]][[10]]
                                                  ('金毛狮王', 45, 1, '18800000001'),
                                                  ('青翼蝠王', 38, 1, '18800000002'),
                                                  ('紫衫龙王', 42, 2, '18800000003'),
                                                  ('光明左使', 37, 1, '18800000004'),
                                                  ('光明右使', 48, 1, '18800000005');

添加镜像

    <!-- 配置阿里云仓库 -->
    <repositories>
        <repository>
            <id>aliyun-repos</id>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>aliyun-repos</id>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

添加mybatis起步依赖

在新工程上操作

        <!--mybatis的起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.3</version>
        </dependency>

添加数据库的驱动依赖

        <!--postgresql驱动依赖-->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>

添加数据库配置

spring:
  application:
    name: springboot-mybatis
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/mybatis
    username: postgres
    password: postgres

创建User实体类

package com.zwh.springbootmybatis.pojo;

public class User {
    
    private Integer id;
    private String name;
    private Short age;
    private Short gender;
    private String phone;

    public User() {
    }

    public User(Integer id, String name, Short age, Short gender, String phone) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Short getAge() {
        return age;
    }

    public void setAge(Short age) {
        this.age = age;
    }

    public Short getGender() {
        return gender;
    }

    public void setGender(Short gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                ", phone='" + phone + '\'' +
                '}';
    }
}

创建数据库交互接口

package com.zwh.springbootmybatis.mapper;

import com.zwh.springbootmybatis.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("select * from user where id = #{id}")
    public User findById(Integer id);
}

创建业务逻辑接口 

package com.zwh.springbootmybatis.service;

import com.zwh.springbootmybatis.pojo.User;

public interface UserService {
    public User findById(Integer id);
}

创建接口的实现类 

package com.zwh.springbootmybatis.service.impl;

import com.zwh.springbootmybatis.mapper.UserMapper;
import com.zwh.springbootmybatis.pojo.User;
import com.zwh.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }
}

处理前端请求 

package com.zwh.springbootmybatis.Controller;

import com.zwh.springbootmybatis.pojo.User;
import com.zwh.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/findById")
    public User findById(Integer id){
        return userService.findById(id);
    }
}

运行 

http://127.0.0.1:8080/findById?id=1

 

mapperserviceimplpojocontroller讲解

在Spring Boot中,mapperserviceimplpojocontroller是分层架构中的关键组件,它们分别负责不同的职责:

  1. Mapper:通常指MyBatis的Mapper接口,用于定义与数据库交互的方法。这些方法的具体实现(如SQL语句)通常放在mapper.xml文件中。Mapper接口通过@Mapper注解标识,并且可以继承BaseMapper等通用接口。

  2. Service:表示业务逻辑层接口,定义了业务逻辑的方法。Service接口通常由ServiceImpl实现,实现类中会调用Mapper接口来执行数据库操作。

  3. ServiceImpl:是Service接口的实现类,负责具体的业务逻辑处理。它通常通过@Service注解标识,并且会注入Mapper接口以获取数据库操作能力。

  4. Pojo(Plain Old Java Object) :表示实体类,通常用于映射数据库表。Pojo类包含字段和对应的getter/setter方法,用于在Java对象与数据库之间进行数据转换。

  5. Controller:负责处理前端请求,作为应用的入口点。Controller通过@Controller@RestController注解标识,并调用Service层的方法来处理业务逻辑。

这些组件共同构成了Spring Boot的分层架构,使得代码结构清晰、易于维护和扩展。


网站公告

今日签到

点亮在社区的每一天
去签到