SpringBoot连接PostgreSQL+MybatisPlus入门案例

12 篇文章 0 订阅
7 篇文章 0 订阅

项目结构

一、Java代码

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>jdservice</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--mybatis‐plus的springboot支持-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>


    </dependencies>
</project>

controller层

package org.example.jd.controller;

import org.example.jd.pojo.TUser;
import org.example.jd.service.TUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "http://localhost:8080")
@RestController
public class UserController {

    @Autowired
    private TUserService tUserService;

    @PostMapping("/api/userLogin")
    public String login(@RequestBody TUser tUser) {
        // 实际业务逻辑处理
        String username = tUser.getUsername();
        String password = tUser.getPassword();

        // 这里可以进行用户名密码验证等操作
        System.out.println("========Login successful=====");
        System.out.println(username + "," + password);
        return "Login successful"; // 返回登录成功信息或者其他响应
    }

    @GetMapping("/api/getUserList")
    public List<TUser> getUserList() {
        List<TUser> tUserList = tUserService.getUserList();
        return tUserList;
    }


}

mapper层

package org.example.jd.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.example.jd.pojo.TUser;

public interface TUserMapper extends BaseMapper<TUser> { //参数为实体类

}

pojo层

package org.example.jd.pojo;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("tuser")   //指定数据库表
public class TUser {
    @TableId(value = "uid") //指定主键
    private int uid;
    private String username;
    private String password;
    private int age;
    private String gender;
    private LocalDate birthday;
    private String address;
}

service层

TUserService 

package org.example.jd.service;

import org.example.jd.pojo.TUser;

import java.util.List;

public interface TUserService {
    List<TUser> getUserList();
}

TUserServiceImp 

package org.example.jd.service;

import org.example.jd.mapper.TUserMapper;
import org.example.jd.pojo.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TUserServiceImp implements TUserService {

    @Autowired
    private TUserMapper tUserMapper;
    @Override
    public List<TUser> getUserList() {
        return tUserMapper.selectList(null);
    }
}

Application启动类

package org.example.jd;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("org.example.jd.mapper") //扫描mapper层
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

TUserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace是mapper层对应的接口名-->
<mapper namespace="org.example.jd.mapper.TUserMapper">

    <!--id是mapper层对应的接口名中对应的方法名-->
<!--    <select id="myFindUserById" resultType="User">-->
<!--        select *-->
<!--        from tb_user-->
<!--        where id = #{id}-->
<!--    </select>-->
</mapper>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--设置驼峰匹配,MybatisPlus默认开启驼峰匹配-->
    <!--    <settings>-->
    <!--        <setting name="mapUnderscoreToCamelCase" value="true"/>-->
    <!--    </settings>-->

</configuration>

application.yml配置文件

server:
  port: 8090
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/myjd
    username: postgres
    password: 123456
    driver-class-name: org.postgresql.Driver


#设置mybatis-plus
mybatis-plus:
  config-location: classpath:mybatis/mybatis-config.xml  #配置文件
  mapper-locations: classpath:mybatis/mapper/*.xml  #设置mapper层对应的接口对应的mapper.xml的路径
  type-aliases-package: org.example.jd.pojo  #设置别名,mapper.xml中resultType="org.example.jd.pojo.TUser"可省去包,即resultType="TUser"
  #开启自动驼峰映射,注意:配置configuration.map-underscore-to-camel-case则不能配置config-location,可写到mybatis-config.xml中
#  configuration:
#    map-underscore-to-camel-case: true

二、SQL

/*
 Navicat Premium Data Transfer

 Source Server         : myPgSQL
 Source Server Type    : PostgreSQL
 Source Server Version : 160003 (160003)
 Source Host           : localhost:5432
 Source Catalog        : myjd
 Source Schema         : public

 Target Server Type    : PostgreSQL
 Target Server Version : 160003 (160003)
 File Encoding         : 65001

 Date: 19/07/2024 22:15:18
*/


-- ----------------------------
-- Table structure for tuser
-- ----------------------------
DROP TABLE IF EXISTS "public"."tuser";
CREATE TABLE "public"."tuser" (
  "uid" int4 NOT NULL,
  "username" varchar(255) COLLATE "pg_catalog"."default",
  "age" int4,
  "gender" varchar(1) COLLATE "pg_catalog"."default",
  "birthday" date,
  "address" varchar(255) COLLATE "pg_catalog"."default",
  "password" varchar(255) COLLATE "pg_catalog"."default"
)
;

-- ----------------------------
-- Records of tuser
-- ----------------------------
INSERT INTO "public"."tuser" VALUES (1, 'jack', 24, '男', '2021-10-19', '深圳', '123');

-- ----------------------------
-- Primary Key structure for table tuser
-- ----------------------------
ALTER TABLE "public"."tuser" ADD CONSTRAINT "user_pkey" PRIMARY KEY ("uid");

三、运行

浏览器或者postman请求地址。

注意:浏览器只能测试get请求,如果有put、post、delete请使用postman测试。

http://localhost:8090/api/getUserList

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
您好!对于使用Spring BootPostgreSQL存储和操作JSON格式数据的问题,您可以按照以下步骤进行操作: 1. 首先,在您的Spring Boot项目中添加PostgreSQL的依赖。您可以在Maven或Gradle配置文件中添加以下依赖项: ```xml <!-- Maven --> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>版本号</version> </dependency> ``` ```groovy // Gradle implementation 'org.postgresql:postgresql:版本号' ``` 2. 确保您已经在PostgreSQL数据库中创建了一个表,该表包含一个JSON类型的列用于存储JSON数据。您可以使用以下DDL语句创建一个表: ```sql CREATE TABLE your_table ( id SERIAL PRIMARY KEY, json_data JSON ); ``` 3. 在您的Spring Boot应用程序中,您可以使用JPA(Java Persistence API)或Spring Data JDBC来访问和操作数据库。 - 如果您选择使用JPA,您需要创建一个实体类来映射到数据库表。在实体类中,您可以使用`@Column(columnDefinition = "json")`注解来指定该字段应该使用JSON数据类型。例如: ```java @Entity @Table(name = "your_table") public class YourEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(columnDefinition = "json") private String jsonData; // Getters and setters } ``` - 如果您选择使用Spring Data JDBC,您可以创建一个简单的POJO类,其中包含一个与数据库表列对应的字段。例如: ```java public class YourEntity { private Long id; private String jsonData; // Getters and setters } ``` 4. 在您的应用程序中,您可以使用JPA的Repository接口或Spring Data JDBC的Repository接口来执行数据库操作。例如,使用JPA的Repository接口: ```java public interface YourRepository extends JpaRepository<YourEntity, Long> { } ``` 5. 现在,您可以在您的业务逻辑中使用Repository接口来存储和检索JSON数据。例如,使用JPA的Repository接口: ```java @Service public class YourService { private final YourRepository yourRepository; public YourService(YourRepository yourRepository) { this.yourRepository = yourRepository; } public void saveJsonData(String jsonData) { YourEntity entity = new YourEntity(); entity.setJsonData(jsonData); yourRepository.save(entity); } public List<YourEntity> getAllEntities() { return yourRepository.findAll(); } } ``` 这样,您就可以使用Spring BootPostgreSQL来存储和操作JSON格式数据了。希望对您有所帮助!如有任何疑问,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小天博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值