搭建 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 項目整合源碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM