从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

本例细化到每一步骤的操作。

网上不太好找详细的mybatis整合postgresql数据库搭建springboot2框架web工程的教程。所以以下我就一步一步详解,写一个细化的傻瓜教程。因为对于初学者来说,教程不够细化,就没有什么可复用性。

以下,照着一步一步操作,可以搭建出来一个web工程。

另外,写教程不附赠源码,就是耍流氓,最后有git地址。

 

 

一、开发环境:

开发IDE:IntelliJ IDEA。

JDK:jdk1.8

框架:springboot2+mybatis

数据库:postgresql

数据:数据就采用之前上传到postgresql库中v6_time_cnty_pts_utf_wgs84表。

 

 

二、工程搭建

1. Create New Project

打开IDEA,Create New Project 。或者已经是打开了一个工程的页面,File——New——Project。总之,新建工程。

 

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

  1. 初始化Spring

如图,选择Spring Initializr;

Project SDK选择JDK(JAVA语言的软件开发包);

保证网络畅通,Next;

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

  1. 工程命名

给自己的工程起个名,Group一般以com.开头,有点像域名,Artifact是工程的名称,两者都以英文命名,且不能有大写字母,这是工程规范。

Type,默认的就是Maven Project,Maven工程管理jar包很便捷。

Language是Java,不用说了。

Packaging是jar,打包编译类型肯定是jar包了。

Java Version是8,JDK的版本是1.8。

Version,版本号是0.0.1-SNAPSHOT,快照版。

Name是根据Artifact生成的,两个一样。

Description是工程描述,可以描述一下。

Package是Group.Artifact,都是自动生成的,,不用管。

这步骤,填下Group和Artifact,next就可以。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

  1. 配置maven依赖

这个步骤是在创建工程的时候,就把一些maven依赖(Dependencies)配置上。

如图所示,点选Developer Tools,勾选Spring Boot DevTools、Lombok、Spring Configuration Processor。

依次把Web中的Spring Web Starter;Template Engines中的Thymeleaf;SQL中的JDBC API、Mybatis Framwork、PostgreSQL Driver都勾选上,点击next。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

稍微介绍下这些依赖都是干什么的。

Spring Boot DevTools:热部署,修改内容,工程自动重启。

Lombok:打日志、注解工具,调试代码用。

Spring Configuration Processor:引入配置的工具。

这三个都是方便写代码的。

 

Spring Web Starter:web工程启动工具。

Thymeleaf:整合前端用的。

 

JDBC API:连数据库的引擎。

Mybatis Framwork:Mybatis框架。

PostgreSQL Driver:pg库引擎。

 

先加这些依赖,不够用的话,以后在配置文件中,也非常好加。

 

  1. 保存工程

Project name就是Artifact的名称,这个不用改,给工程找个地方放,Project location放工程的文件夹,确保这个文件夹名跟Project name一样。点击finish。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

  1. 静待下载依赖

保持网络畅通,下载依赖还需要几分钟,看右下角的进度条就可以了。

当提示,Plugins Suggestion,选择Enable plugins。

当提示,Maven projects need to be imported,选择Enable Auto-Import,如果之前已经配置了maven的自动导入,这步就不会提示了。

 

 

 

三、完善工程结构

创建完的工程长这个样子。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

我们按照规范给它完善一下。

需要添加controller层、dao层、model层、service层(内有Impl层)。

在com.history.gismap上右键——new——package,依次新建package,注意层级关系。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

Package建立完,长这样。

注意层级关系,impl是service下的package,package的命名都需要小写。

点击小齿轮,取消勾选Compack Middle Packages,勾选上的话,会把空的package给折叠了。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

创建完package之后,在各个层(package)上,右键——new——Java Class,新建类。

创建完长这样,接口(interface)和类(class)命名要符合驼峰规则。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

其中MapService是接口(interface),MapServiceImpl是它的实现类(class)。

MapService长这样。

package com.history.gismap.service;

public interface
MapService {
}

MapServiceImpl长这样,继承(implements)了Map Service。

package com.history.gismap.service.impl;



import com.history.gismap.service.MapService;



public class MapServiceImpl implements MapService {

}

 

 

四、完善依赖

把pom.xml打开,缺依赖加依赖,缺配置加配置。

主要改了properties,标注一下编码为utf8。

和dependencies,把缺的一些依赖加上了。

把postgresql的版本号<version>42.2.2</version>加上,注释掉<!--<scope>runtime</scope>-->,因为我不只是运行的时候用这个jar包,我测试的时候也要用。

加上lombok的版本号<version>1.18.8</version>。

加上apache的commons-lang3的jar包,解析json的包,分页插件pagehelper-spring-boot-starter,数据库连接池druid-spring-boot-starter、解析几何geometry对象用的jts包。

现在pom文件长这样,文件路径:D:\gismap\java\gismap\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.1.6.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>com.history</groupId>

    <artifactId>gismap</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <name>gismap</name>

    <description>Demo project for Spring Boot</description>



    <properties>

<!--        标注一下编码为utf8,jdk版本为1.8-->

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <java.version>1.8</java.version>

    </properties>



    <dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-jdbc</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>2.1.0</version>

        </dependency>



        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <scope>runtime</scope>

            <optional>true</optional>

        </dependency>

        <dependency>

            <groupId>org.postgresql</groupId>

            <artifactId>postgresql</artifactId>

            <version>42.2.2</version>

            <!--         <scope>runtime</scope>-->

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-configuration-processor</artifactId>

            <optional>true</optional>

        </dependency>

        <dependency>

            <groupId>org.projectlombok</groupId>

            <artifactId>lombok</artifactId>

            <version>1.18.8</version>

            <optional>true</optional>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>



        <dependency>

            <groupId>org.apache.commons</groupId>

            <artifactId>commons-lang3</artifactId>

            <version>3.4</version>

        </dependency>



        <!--解析json的-->

        <dependency>

            <groupId>com.fasterxml.jackson.core</groupId>

            <artifactId>jackson-core</artifactId>

        </dependency>

        <dependency>

            <groupId>com.fasterxml.jackson.core</groupId>

            <artifactId>jackson-databind</artifactId>

        </dependency>

        <dependency>

            <groupId>com.fasterxml.jackson.datatype</groupId>

            <artifactId>jackson-datatype-joda</artifactId>

        </dependency>

        <dependency>

            <groupId>com.fasterxml.jackson.module</groupId>

            <artifactId>jackson-module-parameter-names</artifactId>

        </dependency>

        <!-- 分页插件 -->

        <dependency>

            <groupId>com.github.pagehelper</groupId>

            <artifactId>pagehelper-spring-boot-starter</artifactId>

            <version>1.2.5</version>

        </dependency>

        <!-- alibaba的druid数据库连接池 -->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid-spring-boot-starter</artifactId>

            <version>1.1.9</version>

        </dependency>

        <!-- 解析几何geometry对象用的-->

        <dependency>

            <groupId>com.vividsolutions</groupId>

            <artifactId>jts</artifactId>

            <version>1.13</version>

        </dependency>







    </dependencies>



    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>



</project>

保持网络畅通,静待maven依赖下载。

查看maven的地方,Project——External Libraries,Maven——Dependencies。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

 

 

五、连接数据库

把D:\gismap\java\gismap\src\main\resources\application.properties删掉,properties有时候连接不上datasource。

新建D:\gismap\java\gismap\src\main\resources\application.yml文件。

 

server:

  port: 8080



#数据库配置

spring:

  datasource:

    #alibaba数据连接池

    type: com.alibaba.druid.pool.DruidDataSource

    #postgresql驱动

    driverClassName: org.postgresql.Driver

    #数据库地址、账号、密码

    url: jdbc:postgresql://127.0.0.1:5432/postgres

    username: postgres

    password: 123456

    druid:

      #初始化连接大小

      initial-size: 8

      #最小空闲连接数

      min-idle: 5

      #最大连接数

      max-active: 10

      #查询超时时间

      query-timeout: 6000

      #事务查询超时时间

      transaction-query-timeout: 6000

      #关闭空闲连接超时时间

      remove-abandoned-timeout: 1800

      filters: stat,config



mybatis:

  #sql映射文件

  mapper-locations: classpath:mapper/*.xml

  #model

  type-aliases-package: com.history.gismap.model

 

其中数据库url、username、password根据自己的写。

Mybatis是映射配置,sql语句都写在xml文件中。

在application.yml的同路径下,新建一个文件夹mapper,右键——New——Directory,D:\gismap\java\gismap\src\main\resources\mapper

在mapper下新建一个文件HistoryGISMapper.xml,右键——New——File,D:\gismap\java\gismap\src\main\resources\mapper\HistoryGISMapper.xml

如下所示。

 

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

六、完善代码

开始逐一完善代码。

1.model类

首先是PointModel,先加两个参数,与数据库对应上,先把流程跑通,springboot要善用注解,@Getter和@Setter,就不用写getter和setter了。

D:\gismap\java\gismap\src\main\java\com\history\gismap\model\PointModel.java

package com.history.gismap.model;



import lombok.Getter;

import lombok.Setter;

import lombok.ToString;



@Getter

@Setter

@ToString

public class PointModel {

    private Integer gId;

    private String nameCh;

}

 

2.Dao类

注意把class改成了interface,加了@Service注释,只新建了一个getCntyPoint的方法,跑下流程,加@Param注释,注释里的gId是sql中的#{gId}。

D:\gismap\java\gismap\src\main\java\com\history\gismap\dao\MapDao.java

package com.history.gismap.dao;



import com.history.gismap.model.PointModel;

import org.springframework.stereotype.Service;



import java.util.List;



@Service

public interface MapDao {

     List<PointModel> getCntyPoint(@Param("gId") Integer gId);

}

 

3.mapper配置

注意mapper 的namespace是dao,查询语句中#{gId}的内容是dao中方法@Param("gId")注释的内容,保持两者一致。

 

<?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.history.gismap.dao.MapDao" >

    <resultMap id="pointModelResult" type="com.history.gismap.model.PointModel">

        <result property="gId" column="gid" jdbcType="BIGINT"/>

        <result property="nameCh" column="name_ch" jdbcType="VARCHAR"/>

    </resultMap>

    <sql id="BASE_TABLE">

    v6_time_cnty_pts_utf_wgs84

  </sql>



    <sql id="BASE_COLUMN">

    gid,name_ch

  </sql>

    <select id="getCntyPoint" resultMap="pointModelResult">

        SELECT

        <include refid="BASE_COLUMN"></include>

        FROM

        <include refid="BASE_TABLE"/>

        WHERE gid=#{gId}

    </select>

</mapper>

 

4.service类

接口

D:\gismap\java\gismap\src\main\java\com\history\gismap\service\MapService.java

package com.history.gismap.service;



import com.history.gismap.model.PointModel;



import java.util.List;



public interface MapService {

    List<PointModel> getCntyPointByGid(Integer gId);

}

实现类,注意注释@Service

D:\gismap\java\gismap\src\main\java\com\history\gismap\service\impl\MapServiceImpl.java

 

package com.history.gismap.service.impl;



import com.history.gismap.dao.MapDao;

import com.history.gismap.model.PointModel;

import com.history.gismap.service.MapService;

import org.springframework.beans.factory.annotation.Autowired;



import java.util.List;

@Service
public class MapServiceImpl implements MapService {

    @Autowired

    private MapDao mapDao;

    @Override

    public List<PointModel> getCntyPointByGid(Integer gId){

        return mapDao.getCntyPoint(gId);

    }

}

 

5. Controller类

获取一条测试下。

D:\gismap\java\gismap\src\main\java\com\history\gismap\controller\MapController.java

package com.history.gismap.controller;



import com.history.gismap.model.PointModel;

import com.history.gismap.service.MapService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;



@Controller

@RequestMapping(value = "/history")

public class MapController {

    @Autowired

    private MapService mapService;

    @ResponseBody

    @GetMapping("/pointmodel")

    public PointModel getPoint(@RequestParam("gid") Integer gId){

        return mapService.getCntyPointByGid(gId).get(0);

    }

}

 

  1. 启动类

注意加上@MapperScan("com.history.gismap.dao"),启动的时候扫描dao包,否则服务没法加载。启动的时候,运行它就行。

D:\gismap\java\gismap\src\main\java\com\history\gismap\GismapApplication.java

 

package com.history.gismap;



import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication

@MapperScan("com.history.gismap.dao")



public class GismapApplication {



    public static void main(String[] args) {

        SpringApplication.run(GismapApplication.class, args);

    }



}

 

 

  1. 测试一下

用IDEA自带的工具测就行,Tools——HTTP Client——Test RESTful Web Service。

 

HTTP method选get,Host/port和Path照着写就行。点击运行下,就出现了结果,{"nameCh":"保德州","gid":1}。

大功告成。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

七、增删改查

说写代码就是增删改查,

那就把增删改查都搞一下吧。

 

1.dao类

package com.history.gismap.dao;

import
com.history.gismap.model.PointModel;
import
org.apache.ibatis.annotations.Param;
import
org.springframework.stereotype.Service;
import
java.util.List;

@Service
public interface MapDao {
    List<PointModel>
getCntyPoint(@Param("gId") Integer gId);
    int
insertCntyPoint(PointModel pointModel);
    int
updateCntyPoint(PointModel pointModel);
    int
deleteCntyPoint(@Param("gId") Integer gId);
}

 

 

 

2.mapper配置

<?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.history.gismap.dao.MapDao" >
    <resultMap
id="pointModelResult" type="com.history.gismap.model.PointModel">
        <result
property="gId" column="gid" jdbcType="BIGINT"/>
        <result
property="nameCh" column="name_ch" jdbcType="VARCHAR"/>
    </resultMap>
    <sql
id="BASE_TABLE">
   
v6_time_cnty_pts_utf_wgs84
 
</sql>

    <sql
id="BASE_COLUMN">
   
gid,name_ch
 
</sql>
    <select
id="getCntyPoint" resultMap="pointModelResult">
       
SELECT
       
<include refid="BASE_COLUMN"></include>
       
FROM
       
<include refid="BASE_TABLE"/>
       
WHERE gid=#{gId}
   
</select>
    <insert
id="insertCntyPoint" parameterType="com.history.gismap.model.PointModel">
       
INSERT INTO
       
<include refid="BASE_TABLE"/>
        <trim
prefix="(" suffix=")" suffixOverrides=",">
            <if
test="gId != null">
               
gid,
           
</if>
            <if
test="nameCh != null">
               
name_ch,
           
</if>
        </trim>
        <trim
prefix="VALUES(" suffix=")" suffixOverrides=",">
            <if
test="gId != null">
               
#{gId, jdbcType=BIGINT},
           
</if>
            <if
test="nameCh != null">
               
#{nameCh, jdbcType=VARCHAR},
           
</if>
        </trim>
    </insert>
    <update
id="updateCntyPoint" parameterType="com.history.gismap.model.PointModel">
       
UPDATE
       
<include refid="BASE_TABLE"/>
       
SET
            name_ch=#{nameCh}
        WHERE
        gid=#{gId}
   
</update>
    <delete
id="deleteCntyPoint" parameterType="com.history.gismap.model.PointModel">
       
DELETE FROM
       
<include refid="BASE_TABLE"/>
       
WHERE
        gid=#{gId}
   
</delete>
</mapper>

 

 

3.service类

package com.history.gismap.service;

import
com.history.gismap.model.PointModel;
import
org.springframework.stereotype.Service;

import
java.util.List;
public interface
MapService {
    List<PointModel>
getCntyPointByGid(Integer gId);
    int
addCntyPoint(PointModel pointModel);
    int
modifyCntyPoint(PointModel pointModel);
    int
removeCntyPoint(Integer gId);

}

 

 

impl

 

package com.history.gismap.service.impl;

import
com.history.gismap.dao.MapDao;
import
com.history.gismap.model.PointModel;
import
com.history.gismap.service.MapService;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Service;

import
java.util.List;
@Service
public class MapServiceImpl implements MapService {
   
@Autowired
   
private MapDao mapDao;
   
@Override
   
public List<PointModel> getCntyPointByGid(Integer gId){
       
return mapDao.getCntyPoint(gId);
   
}
   
@Override
   
public int addCntyPoint(PointModel pointModel){
       
return mapDao.insertCntyPoint(pointModel);
   
}
   
@Override
   
public int modifyCntyPoint(PointModel pointModel){
       
return mapDao.updateCntyPoint(pointModel);
   
}
   
@Override
   
public int removeCntyPoint(Integer gId){
       
return mapDao.deleteCntyPoint(gId);
   
}
}

 

4.Controller类

 

package com.history.gismap.controller;

import
com.history.gismap.model.PointModel;
import
com.history.gismap.service.MapService;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping
(value = "/history")
public class MapController {
   
@Autowired
   
private MapService mapService;
   
@ResponseBody
    @GetMapping
("/pointmodel")
   
public PointModel getPoint(@RequestParam("gid") Integer gId){
       
return mapService.getCntyPointByGid(gId).get(0);
   
}
   
@ResponseBody
    @PostMapping
("/add")
   
public int addPoint(PointModel pointModel){
       
return mapService.addCntyPoint(pointModel);
   
}
   
@ResponseBody
    @PostMapping
("/modify")
   
public int update(PointModel pointModel){
       
return mapService.modifyCntyPoint(pointModel);
   
}
   
@ResponseBody
    @GetMapping
("/remove")
   
public int removetPoint(@RequestParam("gid") Integer gId){
       
return mapService.removeCntyPoint(gId);
   
}
}

 

 

  1. 测试一下

运行GismapApplication。

 

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

查:

http://localhost:8080/history/pointmodel?gid=1

浏览器访问这个网页就行。

增:

用postman,post请求,写好params后,点击send。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

改:

 

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

删:就把我测试这条脏数据删掉。

 

http://localhost:8080/history/remove?gid=14353

 

八、上传代码

 

不留源码都是耍流氓。

 

源码地址:https://github.com/yimengyao13/gismap.git

直接在IDEA中下下来看,File——New——Project from Version Controll——Git

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

填好url,选好Directory(文件夹名称gismap与工程名称gismap保持一致),点击clone下载就成了。

从零开始,构建电子地图网站:0_7_IDEA新建web工程mybatis+postgresql+springboot2

 

 

接下来还有geometry几何对象的增删改查,这个就需要mybatis自定义类型了。下篇继续。