项目源码-SpringBoot项目-创建及使用
Last Updated on 2025年1月17日 by hangzi
一、创建项目
1、打开IDEA
,通过New Project
创建项目,如下图:
2、选择Spring Initializr
,配置好项目信息,点击Next,如下图:
3、选择依赖,点击Create,创建项目成功,如下图:
4、删除一些没啥用的文件及文件夹,只保留源码相关的文件,如下图:
5、最后保留下项目结构是这样的,如下图:
二、使用项目
搭建的项目主体框架是SpringBoot+Mybatis模式
1、修改配置文件格式
和pom.xml排版
每个人都有自己的习惯,我个人的习惯是会修改配置文件格式
和pom.xml排版
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hz</groupId>
<artifactId>SpringBoot-Demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>${project.artifactId}</name>
<description>基于 Java 17 + SpringBoot3 创建的Demo项目</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<hutool.version>5.8.27</hutool.version>
<mysql.version>8.0.33</mysql.version>
<mybatis-plus.version>3.5.9</mybatis-plus.version>
</properties>
<dependencies>
<!--lombok 只在编译期间需要-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!--工具类包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
<!-- mysql数据库连接包-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<!-- mybatis-plus 见:dependencyManagement下管理 start-->
<!-- springboot3 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>
<!-- 分页插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</dependency>
<!-- 代码生成器需要的模版-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<!-- mybatis-plus end -->
<!-- springboot web包(默认是web服务是tomcat) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot test测试包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!-- 通过mybatis-plus-bom管理依赖,减少版本号的冲突 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-bom</artifactId>
<version>${mybatis-plus.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件格式修改,由原始Properties格式:application.properties,修改为YAML格式:application.yml,如下图:
application.yml
内容如下:
# web服务配置
server:
port: 8080
# 给项目添加前缀,这个可以加也可以不加
servlet:
context-path: /demo
spring:
# 项目名称
application:
name: SpringBoot-Demo
# 数据库配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3307/demo?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&allowMultiQueries=true
username: root
password: root
# mybatis
mybatis-plus:
global-config:
db-config:
# 主键ID类型
id-type: none
# 逻辑删除字段名称
# logic-delete-field: deleted
# 逻辑删除-删除值
logic-delete-value: 1
# 逻辑删除-未删除值
logic-not-delete-value: 0
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
检查项目是否能正常启动,如下图:
以User表进行简单增删改查为例
项目结构,如图:
Java三层架构的三个层次:控制层(UserController
),业务逻辑层(UserService
、UserServiceImpl
),数据访问层(UserDao
、UserDao.xml
)
- user表:
CREATE TABLE `user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(100) NOT NULL COMMENT '用户名',
`password` varchar(100) NOT NULL COMMENT '密码',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`update_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE
) COMMENT = '用户表';
User
实体类:
/**
* <p>
* 用户表
* </p>
*
* @author hz
* @since 2025-01-06
*/
@Getter
@Setter
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}
UserMapper
接口类:
/**
* <p>
* 用户表 Mapper 接口
* </p>
*
* @author hz
* @since 2025-01-06
*/
@Mapper
public interface UserMapper extends BaseMapper<User> {
Page<User> listPagedUsers(Page<User> page, UserPageQuery queryParams);
}
UserMapper.xml
mybatis写sql语句的位置:
<?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.hz.mapper.UserMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.hz.model.User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id, username,password,create_time, update_time
</sql>
<!-- 分页列表 -->
<select id="listPagedUsers" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List"/>
FROM
user
<where>
1=1
<if test="queryParams.username != null">
AND username LIKE CONCAT('%',#{queryParams.username},'%')
</if>
</where>
ORDER BY create_time DESC
</select>
</mapper>
UserService
接口类:
/**
* <p>
* 用户表 服务类
* </p>
*
* @author hz
* @since 2025-01-06
*/
public interface IUserService extends IService<User> {
IPage<User> listPagedUsers(UserPageQuery queryParams);
boolean saveUser(User formData);
User getUserFormData(Long id);
boolean updateUser(User formData);
boolean deleteUsers(String ids);
}
UserServiceImpl
实现类:
/**
* <p>
* 用户表 服务实现类
* </p>
*
* @author hz
* @since 2025-01-06
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Override
public IPage<User> listPagedUsers(UserPageQuery queryParams) {
int pageNum = queryParams.getPageNum();
int pageSize = queryParams.getPageSize();
Page<User> page = new Page<>(pageNum, pageSize);
return this.baseMapper.listPagedUsers(page, queryParams);
}
@Override
public boolean saveUser(User formData) {
return this.save(formData);
}
@Override
public User getUserFormData(Long id) {
return this.getById(id);
}
@Override
public boolean updateUser(User formData) {
return this.updateById(formData);
}
@Override
public boolean deleteUsers(String ids) {
Assert.isTrue(StrUtil.isNotBlank(ids), "删除的数据为空");
List<Long> idList = Arrays.stream(ids.split(","))
.map(Long::parseLong)
.toList();
return this.removeByIds(idList);
}
}
UserController
控制层:
/**
* <p>
* 用户表 前端控制器
* </p>
*
* @author hz
* @since 2025-01-06
*/
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final IUserService userService;
/**
* 分页列表
*/
@GetMapping("/page")
public PageResult<User> listPagedUsers(UserPageQuery queryParams ) {
IPage<User> result = userService.listPagedUsers(queryParams);
return PageResult.success(result);
}
/**
* 新增
*/
@PostMapping
public Result saveUser(@RequestBody User formData ) {
boolean result = userService.saveUser(formData);
return Result.judge(result);
}
/**
* 根据id获取详情
*/
@GetMapping("/{id}")
public Result getUserForm(@PathVariable Long id) {
User formData = userService.getUserFormData(id);
return Result.success(formData);
}
/**
* 修改
*/
@PutMapping(value = "/{id}")
public Result updateUser(@RequestBody User formData) {
boolean result = userService.updateUser(formData);
return Result.judge(result);
}
/**
* 删除
*/
@DeleteMapping("/{ids}")
public Result deleteUsers(@PathVariable String ids) {
boolean result = userService.deleteUsers(ids);
return Result.judge(result);
}
}
简单流程过程,如下图:
mybatis-plus快速生成代码:
@SpringBootTest
public class CodeGeneratorTest {
@Test
public void codeGenerator() {
FastAutoGenerator.create("jdbc:mysql://127.0.0.1:3306/demo", "root", "root")
.globalConfig(builder -> builder
.disableOpenDir()
.author("hz")
.dateType(DateType.ONLY_DATE)
.outputDir(Paths.get(System.getProperty("user.dir")) + "/src/main/java")
.commentDate("yyyy-MM-dd")
)
.packageConfig(builder -> builder
.parent("com.hz")
.entity("model")
.mapper("mapper")
.service("service")
.serviceImpl("service.impl")
//自定义mapper.xml文件输出目录
.pathInfo(Collections.singletonMap(OutputFile.xml,Paths.get(System.getProperty("user.dir")) + "/src/main/resources/mapper"))
)
.strategyConfig(builder -> builder
.entityBuilder()
.enableLombok()
)
.execute();
}
}
关注微信公众号『编程与读书』
第一时间了解最新网络动态
关注博主不迷路~