idea2025构建springboot项目能运行的样例

idea2025构建springboot项目能运行的样例

先创建一个swaggerdemo项目,选择maven,这里使用maven3.9.6,java选择17,jar和war随便选,需要安装lombok插件.

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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version>
        <relativePath/>
    </parent>

    <groupId>com.example</groupId>
    <artifactId>swaggerdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>swaggerdemo</name>
    <description>Swagger Demo Project</description>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- OpenAPI (Swagger) -->
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.7.0</version>
        </dependency>

        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>

        <!-- MyBatis Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

spring.application.name=swaggerdemo

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# MyBatis Plus配置
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.mapper-locations=classpath*:/mapper/**/*.xml

# OpenAPI配置
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html

OpenAPIConfig

package com.example.swaggerdemo.config;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenAPIConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Swagger Demo API")
                        .version("1.0")
                        .description("Swagger Demo 项目接口文档")
                        .contact(new Contact()
                                .name("Developer")
                                .email("developer@example.com")
                                .url("http://localhost:8080"))
                        .license(new License().name("Apache 2.0")
                                .url("http://springdoc.org")));
    }
}

AuthController

package com.example.swaggerdemo.controller;

import com.example.swaggerdemo.dto.LoginRequest;
import com.example.swaggerdemo.dto.LoginResponse;
import com.example.swaggerdemo.entity.User;
import com.example.swaggerdemo.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证接口", description = "用户认证相关接口")
public class AuthController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "登录成功"),
            @ApiResponse(responseCode = "401", description = "用户名或密码错误")
    })
    public LoginResponse login(@RequestBody LoginRequest loginRequest) {
        LoginResponse response = new LoginResponse();

        // 使用 UserService 中调用 XML SQL 的方法
        boolean loginSuccess = userService.login(loginRequest.getUsername(), loginRequest.getPassword());

        if (loginSuccess) {
            response.setSuccess(true);
            response.setMessage("登录成功");
            response.setToken("fake-jwt-token");
        } else {
            response.setSuccess(false);
            response.setMessage("用户名或密码错误");
        }

        return response;
    }

    // 添加一个获取用户信息的示例接口
    @GetMapping("/user/{username}")
    @Operation(summary = "根据用户名获取用户信息", description = "根据用户名获取用户详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public User getUserByUsername(@PathVariable String username) {
        // 使用 UserService 调用 XML 中定义的 findByUsername 方法
        return userService.findByUsername(username);
    }
	@GetMapping("/user")
    @Operation(summary = "获取所有用户", description = "获取所有用户接口")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "获取失败")
    })
    public List<User> getAllUsers() {
        // 使用 UserService 调用 XML 中定义的 findByUsername 方法
        return userService.selectAllUsers();
    }
}

LoginRequest

package com.example.swaggerdemo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
@Schema(name = "登录请求参数")
public class LoginRequest {
    @Schema(description = "用户名", example = "admin", required = true)
    private String username;

    @Schema(description = "密码", example = "123456", required = true)
    private String password;
}

LoginResponse

package com.example.swaggerdemo.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
@Schema(name = "登录响应结果")
public class LoginResponse {
    @Schema(description = "是否登录成功")
    private Boolean success;

    @Schema(description = "消息")
    private String message;

    @Schema(description = "token")
    private String token;
}

User

package com.example.swaggerdemo.entity;

import com.baomidou.mybatisplus.annotation.*;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;

@Data
@TableName("user")
@Schema(name = "用户实体")
public class User {
    @TableId(value = "id", type = IdType.AUTO)
    @Schema(description = "用户ID")
    private Long id;

    @Schema(description = "用户名")
    private String username;

    @Schema(description = "密码")
    private String password;

    @Schema(description = "邮箱")
    private String email;

    @TableField(fill = FieldFill.INSERT)
    @Schema(description = "创建时间")
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    @Schema(description = "更新时间")
    private LocalDateTime updateTime;

    @TableLogic
    @Schema(description = "删除标志(0:未删除, 1:已删除)")
    private Integer deleted;
}

UserMapper

package com.example.swaggerdemo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.swaggerdemo.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper extends BaseMapper<User> {

    /**
     * 根据用户名查找用户
     * @param username 用户名
     * @return 用户对象
     */
    User findByUsername(@Param("username") String username);

    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 密码
     * @return 用户对象
     */
    User login(@Param("username") String username, @Param("password") String password);

    /**
     * 查询所有未删除用户
     * @return 用户列表
     */
    List<User> selectAllUsers();

    /**
     * 根据ID查询用户
     * @param id 用户ID
     * @return 用户对象
     */
    User selectById(@Param("id") Long id);

    /**
     * 插入用户
     * @param user 用户对象
     */
    void insertUser(User user);

    /**
     * 更新用户信息
     * @param user 用户对象
     */
    void updateUser(User user);

    /**
     * 逻辑删除用户
     * @param id 用户ID
     */
    void deleteUser(@Param("id") Long id);
}

UserService

package com.example.swaggerdemo.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.swaggerdemo.entity.User;
import com.example.swaggerdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查找用户(使用XML中的SQL)
     * @param username 用户名
     * @return 用户对象
     */
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    /**
     * 用户登录验证(使用XML中的SQL)
     * @param username 用户名
     * @param password 密码
     * @return 登录是否成功
     */
    public boolean login(String username, String password) {
        User user = userMapper.login(username, password);
        return user != null;
    }
	public List<User> selectAllUsers() {
        return userMapper.selectAllUsers();
    }
}

SwaggerdemoApplication

package com.example.swaggerdemo;

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

@SpringBootApplication
@MapperScan("com.example.swaggerdemo.mapper") // 确保扫描到mapper接口
public class SwaggerdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerdemoApplication.class, args);
    }
}

resources\mapper\UserMapper.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">
<mapper namespace="com.example.swaggerdemo.mapper.UserMapper">

    <!-- 通用查询结果映射 -->
    <resultMap id="BaseResultMap" type="com.example.swaggerdemo.entity.User">
        <id column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="password" property="password"/>
        <result column="email" property="email"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
        <result column="deleted" property="deleted"/>
    </resultMap>

    <!-- 通用查询字段 -->
    <sql id="Base_Column_List">
        id, username, password, email, create_time, update_time, deleted
    </sql>

    <!-- 根据用户名查询用户 -->
    <select id="findByUsername" parameterType="string" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM user
        WHERE username = #{username} AND deleted = 0
    </select>

    <!-- 用户登录验证 -->
    <select id="login" parameterType="map" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM user
        WHERE username = #{username} AND password = #{password} AND deleted = 0
    </select>

    <!-- 查询所有未删除用户 -->
    <select id="selectAllUsers" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM user
        WHERE deleted = 0
        ORDER BY create_time DESC
    </select>

    <!-- 根据ID查询用户 -->
    <select id="selectById" parameterType="long" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM user
        WHERE id = #{id} AND deleted = 0
    </select>

    <!-- 插入用户 -->
    <insert id="insertUser" parameterType="com.example.swaggerdemo.entity.User">
        INSERT INTO user(username, password, email, create_time, update_time)
        VALUES (#{username}, #{password}, #{email}, NOW(), NOW())
    </insert>

    <!-- 更新用户信息 -->
    <update id="updateUser" parameterType="com.example.swaggerdemo.entity.User">
        UPDATE user
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <if test="email != null and email != ''">
                email = #{email},
            </if>
            update_time = NOW()
        </set>
        WHERE id = #{id} AND deleted = 0
    </update>

    <!-- 逻辑删除用户 -->
    <update id="deleteUser" parameterType="long">
        UPDATE user
        SET deleted = 1, update_time = NOW()
        WHERE id = #{id}
    </update>

</mapper>

SQL

CREATE TABLE `user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `password` varchar(100) NOT NULL COMMENT '密码',
  `email` varchar(100) DEFAULT NULL COMMENT '邮箱',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` int DEFAULT '0' COMMENT '删除标志(0:未删除, 1:已删除)',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 插入测试数据
INSERT INTO `user` (`username`, `password`, `email`) VALUES 
('admin', '123456', 'admin@example.com'),
('user1', 'password1', 'user1@example.com');
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值