搭建 SpringBoot 项目(前端页面 + 数据库 + 实现源码)
SpringBoot 项目整合源码
SpringBoot 项目整合
一、项目准备
1.1 快速创建 SpringBoot 项目
博客地址:快速搭建 SpringBoot 项目(看完 【 1. 快速创建 SpringBoot 项目】 就可以回到这里了)
1.2 项目结构图如下
1.3 数据表结构图如下
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`admin` bit(1) DEFAULT b'0',
`dept_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
1.4 运行结果
二、项目实现
1. 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.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yy</groupId>
<artifactId>springboot-crud</artifactId>
<version>1.0.1</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- SpringBoot热部署插件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<!--mybatis集成到SpringBoot中的依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 支持使用 Spring AOP 和 AspectJ 进行切面编程。 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- SpringBoot集成FreeMarker的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 配置分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- SpringBoot 打包插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- MyBatis 逆向工程插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>false</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
2. application.properties 配置文件
# 修改端口号
server.port=80
# mysql 4要素
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=admin
#设置SQL打印日志
logging.level.com.yy.mapper=trace
#一般我们会做3个配置,其余默认即可
#暴露session对象的属性
spring.freemarker.expose-session-attributes=true
#配置为传统模式,空值自动处理
spring.freemarker.settings.classic_compatible=true
#重新指定模板文件后缀 springboot 2.2.x 后 默认后缀为 .ftlh
spring.freemarker.suffix=.ftl
3. APP 启动类
package com.yy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
// mybatis 接口扫描注解
@MapperScan("com.yy.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
4. EmployeeController 控制器
package com.yy.controller;
import com.github.pagehelper.PageInfo;
import com.yy.domain.Employee;
import com.yy.qo.EmployeeQueryObject;
import com.yy.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/employee")
public class EmployeeController {
@Autowired
private IEmployeeService employeeService;
@RequestMapping("/list")
public String list(Model model, @ModelAttribute("qo")EmployeeQueryObject qo) {
// mybatis 的分页插件,qo 是页面传过来的模糊条件查询参数以及当前页和每页条数
PageInfo<Employee> pageInfo = employeeService.query(qo);
model.addAttribute("pageInfo", pageInfo);
return "employee/list";
}
}
5. IEmployeeService 接口
package com.yy.service;
import com.github.pagehelper.PageInfo;
import com.yy.domain.Employee;
import com.yy.qo.EmployeeQueryObject;
import java.util.List;
public interface IEmployeeService {
int delete(Long id);
int add(Employee record);
Employee selectById(Long id);
List<Employee> selectAll();
int update(Employee record);
PageInfo<Employee> query(EmployeeQueryObject qo);
}
6. EmployeeServiceImpl 接口
package com.yy.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yy.domain.Employee;
import com.yy.mapper.EmployeeMapper;
import com.yy.qo.EmployeeQueryObject;
import com.yy.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
@Autowired(required = false)
private EmployeeMapper employeeMapper;
@Override
public int delete(Long id) {
return 0;
}
@Override
public int add(Employee record) {
return 0;
}
@Override
public Employee selectById(Long id) {
return null;
}
@Override
public List<Employee> selectAll() {
return null;
}
@Override
public int update(Employee record) {
return 0;
}
@Override
public PageInfo<Employee> query(EmployeeQueryObject qo) {
// 使用 mybatis 分页插件,传入当前页和每页条数
PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
List<Employee> list = employeeMapper.selectForList(qo);
return new PageInfo<>(list);
}
}
7. EmployeeMapper 接口
package com.yy.mapper;
import com.yy.domain.Employee;
import com.yy.qo.EmployeeQueryObject;
import java.util.List;
public interface EmployeeMapper {
int deleteByPrimaryKey(Long id);
int insert(Employee record);
Employee selectByPrimaryKey(Long id);
List<Employee> selectAll();
int updateByPrimaryKey(Employee record);
List<Employee> selectForList(EmployeeQueryObject qo);
}
8. EmployeeMapper 接口
<?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.yy.mapper.EmployeeMapper" >
<resultMap id="BaseResultMap" type="com.yy.domain.Employee" >
<id column="id" property="id" />
<result column="username" property="username" />
<result column="name" property="name" />
<result column="password" property="password" />
<result column="email" property="email" />
<result column="age" property="age" />
<result column="admin" property="admin" />
<result column="dept_id" property="deptId" />
</resultMap>
<delete id="deleteByPrimaryKey" >
delete from employee
where id = #{id}
</delete>
<insert id="insert" useGeneratedKeys="true" keyProperty="id" >
insert into employee (username, name, password, email, age, admin, dept_id)
values (#{username}, #{name}, #{password}, #{email}, #{age}, #{admin}, #{deptId})
</insert>
<update id="updateByPrimaryKey" >
update employee
set username = #{username},
name = #{name},
password = #{password},
email = #{email},
age = #{age},
admin = #{admin},
dept_id = #{deptId}
where id = #{id}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" >
select id, username, name, password, email, age, admin, dept_id
from employee
where id = #{id}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
select id, username, name, password, email, age, admin, dept_id
from employee
</select>
<select id="selectForList" resultMap="BaseResultMap">
select id, username, name, password, email, age, admin, dept_id
from employee
</select>
</mapper>
9. generatorConfig.xml(mybatis 逆向工程)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<context id="mysql" defaultModelType="hierarchical"
targetRuntime="MyBatis3Simple">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表; 一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="false" />
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="UTF-8" />
<!-- 格式化java代码 -->
<property name="javaFormatter"
value="org.mybatis.generator.api.dom.DefaultJavaFormatter" />
<!-- 格式化XML代码 -->
<property name="xmlFormatter"
value="org.mybatis.generator.api.dom.DefaultXmlFormatter" />
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 必须要有的,使用这个配置链接数据库 @TODO:是否可以扩展 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql:///springboot" userId="root" password="admin">
<!-- 这里面可以设置property属性,每一个property属性都设置到配置的Driver上 -->
</jdbcConnection>
<!-- java类型处理器 用于处理DB中的类型到Java中的类型,默认使用JavaTypeResolverDefaultImpl; 注意一点,默认会先尝试使用Integer,Long,Short等来对应DECIMAL和
NUMERIC数据类型; -->
<javaTypeResolver
type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
<!-- true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型 false:默认, scale>0;length>18:使用BigDecimal;
scale=0;length[10,18]:使用Long; scale=0;length[5,9]:使用Integer; scale=0;length<5:使用Short; -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- java模型创建器,是必须要的元素 负责:1,key类(见context的defaultModelType);2,java类;3,查询类
targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制; targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录 -->
<!-- TODO -->
<javaModelGenerator targetPackage="com.yy.domain"
targetProject="src/main/java">
<!-- for MyBatis3/MyBatis3Simple 自动为每一个生成的类创建一个构造方法,构造方法包含了所有的field;而不是使用setter; -->
<property name="constructorBased" value="false" />
<!-- for MyBatis3 / MyBatis3Simple 是否创建一个不可变的类,如果为true, 那么MBG会创建一个没有setter方法的类,取而代之的是类似constructorBased的类 -->
<property name="immutable" value="false" />
<!-- 设置是否在getter方法中,对String类型字段调用trim()方法
<property name="trimStrings" value="true" /> -->
</javaModelGenerator>
<!-- 生成SQL map的XML文件生成器, 注意,在Mybatis3之后,我们可以使用mapper.xml文件+Mapper接口(或者不用mapper接口),
或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的话,这个元素就必须配置
targetPackage/targetProject:同javaModelGenerator -->
<!-- TODO -->
<sqlMapGenerator targetPackage="com.yy.mapper"
targetProject="src/main/resources">
<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 对于mybatis来说,即生成Mapper接口,注意,如果没有配置该元素,那么默认不会生成Mapper接口 targetPackage/targetProject:同javaModelGenerator
type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下): 1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML;
2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中; 3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML;
注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER -->
<!-- TODO -->
<javaClientGenerator targetPackage="com.yy.mapper"
type="XMLMAPPER" targetProject="src/main/java">
<!-- 在targetPackage的基础上,根据数据库的schema再生成一层package,最终生成的类放在这个package下,默认为false -->
<property name="enableSubPackages" value="true" />
<!-- 可以为所有生成的接口添加一个父接口,但是MBG只负责生成,不负责检查 <property name="rootInterface"
value=""/> -->
</javaClientGenerator>
<!-- TODO -->
<table tableName="employee">
<property name="useActualColumnNames" value="false"/>
<property name="constructorBased" value="false" />
<generatedKey column="id" sqlStatement="JDBC" />
</table>
</context>
</generatorConfiguration>
10. list.ftl (FreeMaker模板页面,你也可以使用其他页面)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>员工管理</title>
<#include "/common/link.ftl">
</script>
</head>
<body class="hold-transition skin-black sidebar-mini">
<div class="wrapper">
<span id="time" style="display: none">${time}</span>
<#include "/common/navbar.ftl">
<!--菜单回显-->
<#assign currentMenu="employee"/>
<#include "/common/menu.ftl">
<div class="content-wrapper">
<section class="content-header">
<h1>员工管理</h1>
</section>
<section class="content">
<div class="box">
<!--高级查询--->
<div style="margin: 10px;">
<form class="form-inline" id="searchForm" action="/employee/list" method="post">
<input type="hidden" name="currentPage" id="currentPage" value="1">
<div class="form-group">
<label for="keyword">关键字:</label>
<input type="text" class="form-control" value="${qo.keyword}" name="keyword"
placeholder="请输入姓名/邮箱">
</div>
<div class="form-group">
<label for="dept"> 部门:</label>
<select class="form-control" id="dept" name="deptId">
<option value="">全部</option>
<#list departments as department>
<option value="${department.id}" ${(department.id == qo.deptId) ?
string('selected', '')}>${department.name}</option>
</#list>
</select>
</div>
<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-search"></span>
查询
</button>
<a href="/employee/input" class="btn btn-success btn-input">
<span class="glyphicon glyphicon-plus"></span> 添加
</a>
<a href="/employee/exportXls" class="btn btn-warning">
<span class="glyphicon glyphicon-download"></span> 导出
</a>
<a href="#" class="btn btn-warning btn-import">
<span class="glyphicon glyphicon-upload"></span> 导入
</a>
</form>
</div>
<div class="box-body table-responsive ">
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th><input type="checkbox" id="allCb"></th>
<th>编号</th>
<th>用户名</th>
<th>真实姓名</th>
<th>邮箱</th>
<th>年龄</th>
<th>管理员</th>
<th>部门</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<#list pageInfo.list as employee>
<tr>
<td><input type="checkbox" class="cb"></td>
<td>${employee_index + pageInfo.startRow}</td>
<td>${employee.username}</td>
<td>${employee.name}</td>
<td>${employee.email}</td>
<td>${employee.age}</td>
<td>${(employee?? && employee.admin) ? string('是', '否')}</td>
<td>${employee.department.name}</td>
<td>
<a href="/employee/input?id=${employee.id}"
class="btn btn-info btn-xs btn_redirect">
<span class="glyphicon glyphicon-pencil"></span> 编辑
</a>
<a data-url="/employee/delete?id=${employee.id}"
class="btn btn-danger btn-xs btn-delete">
<span class="glyphicon glyphicon-trash"></span> 删除
</a>
</td>
</tr>
</#list>
</tbody>
</table>
<!-- 分页 -->
<#include "/common/page.ftl">
</div>
</div>
</section>
</div>
<#include "/common/footer.ftl">
</div>
</body>
</html>
11. banner.text
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||_ \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
佛祖保佑 永无BUG
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
总结
以上就是 SpringBoot 项目搭建的介绍了,代码仅供参考,欢迎讨论交流。
SpringBoot 项目搭建详细介绍请看我上一篇博客
博客地址:SpringBoot 项目整合源码