美文网首页
Springboot搭建简易论坛1

Springboot搭建简易论坛1

作者: charmingBueaty | 来源:发表于2020-10-13 11:12 被阅读0次

项目介绍:使用springboot搭建一个简单的论坛,包括发布说说、图片、评论、收藏、点赞、关注等简单的功能。项目所使用的技术包括springboot、mybatis、maven等。整个项目采用前后端分离的方式:前端采用vue、后端Java。

一. 搭建项目结构

  1. 新建项目
    IDEA -> new -> project 选择maven,选择jdk1.8 ->next->输入项目名称,我这里是forum(论坛)->finish等待项目创建完毕


    CreateProject
    ProjectName
  2. 导入依赖
    在pom.xml文件中导入目前所需要的依赖
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--springboot web应用必须导入的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--用来连接MySQL数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--阿里巴巴德鲁伊数据库连接池,最大化的利用数据库连接-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <!--mybatis依赖,用来编写sql-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

说明:其中阿里巴巴德鲁伊数据库连接池原理不需要关心,这个在项目最开始的时候就会进行配置而且配置完成后基本不需要改动,只需要了解它是用来处理数据库连接的就可以了。

  1. 配置mybatis-generator,用于逆向工程生成代码。在pom.xml文件中<project></project>标签内添加如下插件
 <build>
        <pluginManagement>
            <!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- load mybatis plugin-->
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.5</version>
                    <dependencies>
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.5</version>
                        </dependency>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>8.0.13</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>mybatis generator</id>
                            <phase>package</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <!-- allow move the generation file-->
                        <verbose>true</verbose>
                        <!-- allow overwrite file-->
                        <overwrite>false</overwrite>
                        <configurationFile>
                            src/main/resources/mybatis-generator.xml
                        </configurationFile>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

说明:至此目前所需要的依赖、插件配置完成,完整的pom文件内容为

<?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>forum</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--springboot web应用必须导入的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--用来连接MySQL数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--阿里巴巴德鲁伊数据库连接池,最大化的利用数据库连接-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.3</version>
        </dependency>
        <!--mybatis依赖,用来编写sql-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- load mybatis plugin-->
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.5</version>
                    <dependencies>
                        <dependency>
                            <groupId>org.mybatis.generator</groupId>
                            <artifactId>mybatis-generator-core</artifactId>
                            <version>1.3.5</version>
                        </dependency>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>8.0.13</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>mybatis generator</id>
                            <phase>package</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <!-- allow move the generation file-->
                        <verbose>true</verbose>
                        <!-- allow overwrite file-->
                        <overwrite>false</overwrite>
                        <configurationFile>
                            src/main/resources/mybatis-generator.xml
                        </configurationFile>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
  1. 配置项目,主要配置端口号、阿里巴巴德鲁伊数据库连接池、mybatis等
    在src/main/resources下新建application.properties文件配置项目
server.port=8888
#配置mybatis自动生成文件配置文件的地址
mybatis.mapper-locations=classpath:mapping/*.xml

#使用springboot自带的datasource配置方式
spring.datasource.name=forum
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/forum
spring.datasource.username=root
spring.datasource.password=root

#使用druid数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver

说明:这些配置基本固定,这里的数据库连接池没有进行详细的配置,在项目启动时没有配置的配置项全部以默认的参数自动配置,如果需要详细的配置可以按如下进行配置(本项目使用默认配置足以)

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  1. 新建数据库forum,字符编码为utf8mb4(使用IDEA创建数据库时,默认就是utf8mb4,直接输数据库名称即可)打开数据库控制台


    打开控制台

    输入一下数据库脚本点击左侧绿色三角号运行脚本创建user_info和user_pwd表

-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info`  (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户姓名',
  `account` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户账号',
  `age` int(11) NOT NULL DEFAULT 0,
  `gender` tinyint(1) NOT NULL DEFAULT 0 COMMENT '用户性别,默认0,1为男,2为女',
  `user_img` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户头像',
  `telephone` varchar(15) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户电话',
  `status` tinyint(1) NOT NULL DEFAULT 0 COMMENT '用户账户状态默认为0,为1可用,为2不可用',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `telephone_index`(`telephone`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for user_pwd
-- ----------------------------
DROP TABLE IF EXISTS `user_pwd`;
CREATE TABLE `user_pwd`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL DEFAULT 0 COMMENT '关联用户表的id',
  `user_password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用户密码,使用MD5进行加密',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact;
  1. 创建mybatis-generator.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>
    <!--    <classPathEntry location="/Program Files/IBM/SQLLIB/java/db2java.zip" />-->
    <!--database connection address and account password-->
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/forum?serverTimezone=GMT&amp;nullCatalogMeansCurrent=true"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- the position of generate DataObject class-->
        <javaModelGenerator targetPackage="com.forum.dataobject" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- the position of reject file-->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- the position of generate Dao class file-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.forum.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--            generate table and className-->
        <table tableName="user_info" domainObjectName="UserDao"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false"
               selectByExampleQueryId="false"/>
        <table tableName="user_pwd" domainObjectName="UserPasswordDao"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false"
               selectByExampleQueryId="false"/>
    </context>
</generatorConfiguration>

执行mybatis-generator插件,步骤如下

1
2
在命令行中填写mybatis-generator:generate -e
3
点击ok之后再点击右上角执行
执行generator插件
执行完之后会看到自动生成的文件。
自动生成的文件
说明:1.dao包下面都是接口,在我们执行数据库操作时直接调用里面相应的接口,在底层就会通过mybatis去操作数据库,对应的sql在resources/mapping下。2.databoject包下面的实体类是与数据库表一一对应的,其中的变量对应表中的字段。
  1. 创建springboot的入口类App
    在com.forum包下创建类App
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.forum.dao")
public class App {
   public static void main(String[] args) {
       SpringApplication.run(App.class, args);
   }
}

至此准备工作已经完成,可以运行项目,如果没有任何报错信息就可以进行下一步了。

相关文章

网友评论

      本文标题:Springboot搭建简易论坛1

      本文链接:https://www.haomeiwen.com/subject/bywmpktx.html