当前位置: 首页 > news >正文

springboot+mybatisplus+postgis实现几何点和线串增删改查分页

postgis类型介绍

对象分类描述
POINT
MULTIPOINT多点
LINESTRING线
LINEARRING线环
MULTILINESTRING点串
POLYGON
MULTIPOLYGON多面
POLYHEDRALSURFACE多面体表面
TRIANGLE三角形
TIN不规则三角网
CIRCULARSTRING曲线串
MULTICURVE多(曲)线
MULTISURFACE多面
GEOMETRYCOLLECTION复合对象

实现点、线环的增删改查分页

1.添加pom依赖

 <!-- postgresql -->
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
            </dependency>
            <!-- PostGis -->
            <dependency>
                <groupId>net.postgis</groupId>
                <artifactId>postgis-jdbc</artifactId>
                <version>2.5.0</version>
            </dependency>
            <!-- 分页插件 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.12</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.mybatis.spring.boot</groupId>
                        <artifactId>mybatis-spring-boot-starter</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>

2.yml配置文件

spring:
  datasource:
    username: root
    password: 1234
    url: jdbc:postgresql://127.0.0.1:5432/db?useUnicode=true&characterEncoding=utf8&currentSchema=public&stringtype=unspecified
    driver-class-name: org.postgresql.Driver
    type: com.alibaba.druid.pool.DruidDataSource  #数据源类型
    initial-size: 5
    min-idle: 5
    max-active: 50
    max-wait: 60000
mybatis:
  type-aliases-package: com.cherry.manager.entity # 所有POJO类所在包路径
  mapper-locations: classpath:mapper/*.xml # mapper映射文件 logImpl
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    cache-enabled: true
    map-underscore-to-camel-case: true
swagger:
  enable: true
pagehelper:
  helper-dialect: postgresql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

响应结果类:
JSONFormatter.class

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

import java.lang.reflect.Type;
import java.util.List;

/**
 * JSONFormatter converts objects to JSON representation and vice-versa. This
 * class depends on Google's GSON library to do the transformation. This class
 * is not thread-safe.
 */
public final class JSONFormatter {

    /**
     * FieldNamingPolicy used by the underlying Gson library. Alter this
     * property to set a fieldnamingpolicy other than
     * LOWER_CASE_WITH_UNDERSCORES used by PayPal REST APIs
     */
    private static FieldNamingPolicy FIELD_NAMING_POLICY = FieldNamingPolicy.IDENTITY;
    /**
     * Gson
     */
    public static Gson GSON = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd HH:mm:ss")
//			.setPrettyPrinting() // beautify format
        .setFieldNamingPolicy(FIELD_NAMING_POLICY).create();

    /*
     * JSONFormatter is coupled to the stubs generated using the SDK generator.
     * Since PayPal REST APIs support only JSON, this class is bound to the
     * stubs for their json representation.
     */
    private JSONFormatter() {
    }

    /**
     * Set a format for gson FIELD_NAMING_POLICY. See {@link FieldNamingPolicy}
     *
     * @param FIELD_NAMING_POLICY
     */
    public static final void setFIELD_NAMING_POLICY(
        FieldNamingPolicy FIELD_NAMING_POLICY) {
        GSON = new GsonBuilder().setPrettyPrinting()
            .setFieldNamingPolicy(FIELD_NAMING_POLICY).create();
    }

    /**
     * Converts a Raw Type to JSON String
     *
     * @param <T> Type to be converted
     * @param t   Object of the type
     * @return JSON representation
     */
    public static <T> String toJSON(T t) {
        return GSON.toJson(t);
    }

    /**
     * Converts a Raw Type to JSON String
     *
     * @param <T> Type to be converted
     * @param t   Object of the type
     * @param e   Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
     * @return JSON representation
     */
    public static <T> String toJSON(T t, Type e) {
        return GSON.toJson(t, e);
    }

    /**
     * Converts a JSON String to object representation
     *
     * @param <T>            Type to be converted
     * @param responseString JSON representation
     * @param clazz          Target class
     * @return Object of the target type
     */
    public static <T> T fromJSON(String responseString, Class<T> clazz) {
        T t = null;
        if (clazz.isAssignableFrom(responseString.getClass())) {
            t = clazz.cast(responseString);
        } else {
            t = GSON.fromJson(responseString, clazz);
        }
        return t;
    }

    /**
     * Converts a JSON String to object representation
     *
     * @param <T>            Type to be converted
     * @param responseString String of the type
     * @param e              Type typeOfSrc = new TypeToken&lt;Collection&lt;Foo&gt;&gt;(){}.getType();
     * @return JSON representation
     */
    public static <T> T fromJSON(String responseString, Type clazz) {
        return GSON.fromJson(responseString, clazz);
    }

    /**
     * Converts a JSON Element to object representation
     *
     * @param <T>      Type to be converted
     * @param response JSON element
     * @param clazz    Target class
     * @return Object of the target type
     */
    public static <T> T fromJSON(JsonElement response, Class<T> clazz) {
        return GSON.fromJson(response, clazz);
    }

    /**
     * Converts a JSON Element to list representation
     *
     * @param <T>      Type to be converted
     * @param response JSON element
     * @param clazz    Target class
     * @return Object of the target type
     */
    public static <T> List<T> fromList(JsonElement response, Class<T> clazz) {
        return GSON.fromJson(response, new JSONList<T>(clazz));
    }

    /**
     * Converts a JSON String to list representation
     *
     * @param <T>      Type to be converted
     * @param response JSON element
     * @param clazz    Target class
     * @return Object of the target type
     */
    public static <T> List<T> fromList(String response, Class<T> clazz) {
        return GSON.fromJson(response, new JSONList<T>(clazz));
    }
}

JSONList.class

import com.google.gson.internal.$Gson$Types;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class JSONList<T> implements ParameterizedType {

    final Type type;
    private Class<? super T> wrapped;

    public JSONList(Class<T> cls) {
        this.wrapped = cls;
        this.type = null; //getSuperclassTypeParameter(cls);
    }

    /**
     * Returns the type from super class's type parameter in
     */
    static Type getSuperclassTypeParameter(Class<?> subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    }

    @Override
    public Type[] getActualTypeArguments() {
        return new Type[]{wrapped};
    }

    @Override
    public Type getOwnerType() {
        return type;
    }

    @Override
    public Type getRawType() {
        return List.class;
    }

}

ServiceCodeEnum.class

import org.slf4j.helpers.MessageFormatter;
import org.springframework.http.HttpStatus;

public enum ServiceCodeEnum implements ServiceCodeInterface {

    /**
     * 执行成功 200
     */
    SUCCESS(HttpStatus.OK.value(), "执行成功"),

    /**
     * 参数异常 400
     */
    PARAM_ERROR(HttpStatus.BAD_REQUEST.value(), "参数异常"),

    /**
     * 数据校验错误 400
     */
    VALIDATOR_ERROR(HttpStatus.BAD_REQUEST.value(), "<strong>请求数据不合法:</strong><br>{}"),

//    /**
//     * 非法请求/Token超时 401
//     */
//    AUTH_CHECK_FIAL(HttpStatus.UNAUTHORIZED.value(), "Illegal request/link invalid"),


    /**
     * token 为空 401
     */
    TOKEN_IS_NULL(HttpStatus.UNAUTHORIZED.value(), "身份令牌(token)不能为空"),

    /**
     * token 身份令牌(token)有误 401
     */
    TOKEN_IS_ERROR(HttpStatus.UNAUTHORIZED.value(), "身份令牌(token)有误"),

    /**
     * 登录超时 401
     */
    LOGIN_TIME_OUT(HttpStatus.UNAUTHORIZED.value(), "登录超时,请重新登录"),

    /**
     * 当前账号在其他设备上登录 401
     */
    OTHER_LOGIN(HttpStatus.UNAUTHORIZED.value(), "当前账号在其他设备上登录"),

    /**
     * 无权限 403
     */
    FORBIDDEN(HttpStatus.FORBIDDEN.value(), "暂无权限,请联系管理员授权"),

    /**
     * 资源不存在 404
     */
    NOT_FOUND(HttpStatus.NOT_FOUND.value(), "您请求的资源不存在"),


    /**
     * 处理请求方式非法 405
     */
    ILLEGAL_WAY_ERROR(HttpStatus.METHOD_NOT_ALLOWED.value(), "请求方式非法"),

    /**
     * 数据已存在,数据库唯一索引抛出 409
     */
    DATA_IS_EXISTS(HttpStatus.CONFLICT.value(), "数据库数据已存在,请检查参数"),

    /**
     * 处理自定义异常 412
     */
    HANDLING_ERROR(HttpStatus.PRECONDITION_FAILED.value(), "请求业务异常"),

    /**
     * 系统异常 - 后台报错 500
     */
    SYS_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "未知异常,请联系管理员"),

    /**
     * 远程接口调用失败 500
     */
    HTTP_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "远程接口调用失败"),

    /**
     * 数据保存失败
     */
    DATA_SAVE_FAIL(1002, "Failed to save data"),

    /**
     * 上传文件异常
     */
    FILE_UPLOAD_SIZE(1003, "MaxUploadSize:Please contact the administrator!"),

    DATA_IS_NULL(1004, "数据不存在"),

    DATA_NOT_NULL(1005, "子级存在数据,请先删除子级数据!"),

    CLASSIFICATION_NAME_IS_EXISTS(1006, "类别名称已经存在!"),

    ROUTE_NAME_IS_EXISTS(1007, "路由名称或路径已经存在!"),
    INTERFACE_PATH_IS_EXISTS(1008, "接口路径已经存在!"),

    /**
     * ---------------------------------------------------- 数据库 ----------------------------------------------------
     */


    TREE_FIRST_NODE_IS_ZERO(1003, "树形结构的第一级节点数据不能为‘0’"),


    /**
     * ---------------------------------------------------- 用户相关 ----------------------------------------------------
     */
    FILE_IS_EMPTY(1000001, "您上传的文件为空,路径:{}"),
    ONLY_ZIP(1000002, "仅支持Zip上传"),
    FILE_IS_LONG(1000003, "文件超过{}M"),
    CHECK_FILE_MD5(1000004, "文件MD5无效"),

    PASSWORD_MODIFY(11003, "密码已修改,请重新登录"),

    NO_PROJECT_MANAGER_AUTHORITY(11000, "您没有权限管理当前项目数据"),
    USER_NOT_HAS_ROLE(11009, "您暂无角色信息,请联系管理员分配"),

    USER_NOT_FOUND(11001, "用户不存在"),
    ORI_PASSWORD_ERROR(11002, "旧密码输入有误"),
    PASSWORD_ERROR(11003, "密码输入有误"),

    SMS_CODE_ERROR(11005, "验证码输入有误,请重新输入"),
    USER_NOT_USED(11006, "用户未启用或者被锁定"),
    PASSWORD_IS_NULL(11007, "密码为空"),
    USERNAME_CANNOT_IS_MOBILE_OR_EMAIL(11008, "用户名不可为手机号或邮箱"),
    MOBILE_MISMATCH(11009, "手机号不匹配"),
    USER_IS_USERD(11010, "该账户已经激活,请勿重复操作"),

    CHECK_PASSWORD_ERROR(11011, "密码校验失败"),


    FILE_EXISTS(11000, "文件已存在,请检查版本号"),
    /**
     * ---------------------------------------------------- 用户相关 ----------------------------------------------------
     */

    PARENT_ID_CANNOT_SELF_OR_CHILD(12001, "父节点不能为自身或子节点"),

    /**
     * ---------------------------------------------------- minio相关 ----------------------------------------------------
     */
    MINIO_BUCKET_NOT_EXISTS(1600, "文件服务器存储空间不存在"),
    MINIO_DOWNLOAD_ERROR(1601, "文件服务器下载文件失败"),
    MINIO_DELETE_ERROR(1602, "文件服务器删除文件失败"),

    /**
     * ---------------------------------------------------- 视频相关 ----------------------------------------------------
     */
    VIDEO_NOT_FOUND(18001, "视频不存在"),

    /**
     * ---------------------------------------------------- 华丽的分割线 ----------------------------------------------------
     */
    INVALID_OPERATION(9999, "illegal operation"),

    /**
     * 项目授权码 失效 98401
     */
    AUTHORIZATION_CODE_OUT(98401, "项目授权码无效,请联系管理员授权"),
    /**
     * 项目授权码 为空 98401
     */
    AUTHORIZATION_CODE_IS_NULL(98401, "项目暂未授权,请联系管理员授权"),
    /**
     * 项目授权码 无效
     */
    AUTHORIZATION_CODE_ERROR(98500, "项目授权码无效,请联系管理员授权"),
    ;
    /**
     * 错误码
     */
    private final int code;

    /**
     * 错误信息
     */
    private final String message;

    /**
     * 重写构造方法
     *
     * @param code    异常码
     * @param message 异常消息
     */
    ServiceCodeEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public String getMessage(String... args) {
        if (args != null && args.length > 0) {
            return MessageFormatter.arrayFormat(message, args).getMessage();
        }
        return message;
    }

}

ServiceCodeInterface.class

package com.cherry.common.result;

/**
 * 错误码枚举
 */
public interface ServiceCodeInterface {
    
    public int getCode();
    
    public String getMessage(String... args);

    public String getMessage();

}

ServiceResponse.class

package com.cherry.common.result;

import com.cherry.common.gosn.JSONFormatter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel(description = "响应结果公共格式")
public class ServiceResponse<R> {

    /**
     * 状态码
     */
    @ApiModelProperty("状态码")
    protected Integer status;

    /**
     * 结果载体
     */
    @ApiModelProperty("结果载体")
    protected R data;

    /**
     * 描述
     */
    @ApiModelProperty("结果描述")
    protected String message;

    public ServiceResponse() {
        this(null);
    }

    public ServiceResponse(R result) {
        this(result, ServiceCodeEnum.SUCCESS);
    }


    public ServiceResponse(R result, Integer status, String message) {
        this.status = status;
        this.data = result;
        this.message = message;
    }

    public ServiceResponse(R result, ServiceCodeInterface code) {
        this.status = code.getCode();
        this.data = result;
        this.message = code.getMessage();
    }

    /**
     * Construct a successful response with given object.
     *
     * @return constructed server response
     */
    public static <T> ServiceResponse<T> ofSuccess() {
        return new ServiceResponse<T>();
    }

    /**
     * Construct a successful response with given object.
     *
     * @param result result object
     * @param <T>    type of the result
     * @return constructed server response
     */
    public static <T> ServiceResponse<T> ofSuccess(T result) {
        return new ServiceResponse<T>(result);
    }

    /**
     * Construct a failed response with given exception.
     *
     * @return constructed server response
     */
    public static <T> ServiceResponse<T> ofFailure() {
        return new ServiceResponse<T>(null, ServiceCodeEnum.PARAM_ERROR);
    }

    /**
     * Construct a failed response with given exception.
     *
     * @param code additional message of the failure
     * @return constructed server response
     */
    public static <T> ServiceResponse<T> ofFailure(Integer code, String desc) {
        return new ServiceResponse<T>(null, code, desc);
    }

    /**
     * 重载
     *
     * @param code
     * @param <T>
     * @return
     */
    public static <T> ServiceResponse<T> ofFailure(ServiceCodeInterface code) {
        return new ServiceResponse<T>(null, code);
    }

    /**
     * Construct a failed response with given exception.
     *
     * @param code cause of the failure
     * @param desc cause of the failure
     * @return constructed server response
     */
    public static <T> ServiceResponse<T> ofFailure(T result, Integer code, String desc) {
        return new ServiceResponse<T>(result, code, desc);
    }

    /**
     * 重载
     *
     * @param result
     * @param code
     * @param <T>
     * @return
     */
    public static <T> ServiceResponse<T> ofFailure(T result, ServiceCodeInterface code) {
        return new ServiceResponse<T>(result, code);
    }

    @Override
    public String toString() {
        return JSONFormatter.toJSON(this);
    }

}

创建数据库

CREATE TABLE public.ftest (
	id int4 NOT NULL,
	geom postgis.geometry NULL,
	CONSTRAINT ftest_pkey PRIMARY KEY (id)
);

控制层:

import com.cherry.common.result.ServiceResponse;
import com.github.pagehelper.PageInfo;
import com.cherry.manager.entity.Ftest;
import com.cherry.manager.service.FtestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * (Ftest)表控制层
 *
 * @since 2022-09-22 15:39:05
 */
@Api(tags = "")
@RestController
@RequestMapping("ftest")
@CrossOrigin
public class FtestController {

    @Autowired
    FtestService service;

    /**
     * 新增记录
     *
     * @param entity 数据实体
     * @return 新增记录
     */
    @ApiOperation(value = "新增记录", notes = "新增记录")
    @PostMapping(value = "/point", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Ftest> addPoint(@RequestBody @ApiParam("json格式对象") Ftest entity) {
        service.savePoint(entity);
        return ServiceResponse.ofSuccess(entity);
    }

    @ApiOperation(value = "新增记录", notes = "新增记录")
    @PostMapping(value = "/points", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Ftest> addPoints(@RequestBody @ApiParam("json格式对象") Ftest entity) {
        service.savePoints(entity);
        return ServiceResponse.ofSuccess(entity);
    }

    /**
     * 删除记录
     *
     * @param ids ids
     * @return 删除结果
     */
    @ApiOperation(value = "删除记录", notes = "删除记录")
    @DeleteMapping(value = "/{ids}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Boolean> delete(@PathVariable("ids") @ApiParam(value = "删除的id", required = true) String... ids) {
        return ServiceResponse.ofSuccess(service.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 修改记录
     *
     * @param entity 数据实体
     * @return 新增结果
     */
    @ApiOperation(value = "修改记录", notes = "修改记录")
    @PutMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Boolean> update(@RequestBody @ApiParam(value = "json格式对象", required = true) Ftest entity) {
        return ServiceResponse.ofSuccess(service.updateEntityById(entity));
    }

    /**
     * 分页查询
     *
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping(value = "page/{current}/{pageSize}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<PageInfo<Ftest>> page(@PathVariable("current") int current,
                                        @PathVariable("pageSize") int pageSize) {
        return ServiceResponse.ofSuccess( service.getPageInfo(current, pageSize));
    }

    /**
     * 查询列表
     *
     * @return 搜索结果集
     */
    @ApiOperation(value = "查询列表", notes = "查询列表")
    @GetMapping(value = "/list", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<List<Ftest>> list() {
        return ServiceResponse.ofSuccess(service.listEntity());
    }

    /**
     * 查询详情
     *
     * @param id id
     * @return 查询结果
     */
    @ApiOperation(value = "查询详情", notes = "查询详情")
    @GetMapping(value = "/info/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<Ftest> info(@PathVariable("id") @ApiParam(value = "查询的ID", required = true) Integer id) {
        return ServiceResponse.ofSuccess(service.getEntityById(id));
    }

    /**
     * 根据id集合查询
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "根据id集合查询", notes = "根据id集合查询")
    @GetMapping(value = "/listByIds/{ids}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ServiceResponse<List<Ftest>> listByIds(@PathVariable("ids") @ApiParam(value = "查询的ID", required = true) String... ids) {
        return ServiceResponse.ofSuccess(service.listEntityByIds(Arrays.asList(ids)));
    }

}

entity实体类

package com.cherry.manager.entity;

import java.io.Serializable;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;

/**
 * (Ftest)实体类
 *
 * @since 2022-09-22 15:50:00
 */
@Data
@EqualsAndHashCode
@ToString(callSuper = true)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@TableName("ftest")
public class Ftest implements Serializable {
    private static final long serialVersionUID = 286631027980693537L;
    
                                                                                                                
                                    
    @ApiModelProperty(value = "${column.comment}")
    @TableField(value = "id")
    private Integer id;
                                                                                                                                                                                                    
                                    
    @ApiModelProperty(value = "${column.comment}")
    @TableField(value = "geom")
    private String geom;

    @ApiModelProperty(value = "点集合")
    @TableField(exist = false)
    private Point[] points;

    @ApiModelProperty(value = "点集合")
    @TableField(exist = false)
    private Point[][] linePoints;

    @ApiModelProperty(value = "geomObject")
    @TableField(value = "geomObject")
    private JSONObject geomObject;
                                                                                    
}

dao层

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cherry.manager.entity.Ftest;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * (Ftest)表数据库访问层
 *
 * @since 2022-09-22 15:39:05
 */
@Mapper
public interface FtestDao extends BaseMapper<Ftest> {
    void savePoint(@Param("id") Integer id, @Param("points") String points);

    Boolean updateEntityById(@Param("id") Integer id, @Param("pointStr") String pointStr);

    List<Ftest> selectAll();

    Ftest getEntityById(@Param("id") Integer id);

    List<Ftest> listEntityByIds(@Param("ids") List<String> ids);

    IPage<Ftest> pageEntity(Page<Ftest> pageQuery);
}

service接口层:

import com.baomidou.mybatisplus.extension.service.IService;
import com.cherry.manager.entity.Ftest;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * (Ftest)表服务接口
 *
 * @since 2022-09-22 15:39:06
 */
public interface FtestService extends IService<Ftest> {

    void savePoint(Ftest entity);

    void savePoints(Ftest entity);

    Boolean updateEntityById(Ftest entity);

    List<Ftest> listEntity();

    Ftest getEntityById(Integer id);

    List<Ftest> listEntityByIds(List<String> asList);

    PageInfo<Ftest> getPageInfo(int current, int pageSize);
}

serviceImpl层:

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cherry.manager.entity.Ftest;
import com.cherry.manager.dao.FtestDao;
import com.cherry.manager.entity.Point;
import com.cherry.manager.service.FtestService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * (Ftest)表服务实现类
 *
 * @since 2022-09-22 15:39:06
 */
@Slf4j
@Service
public class FtestServiceImpl extends ServiceImpl<FtestDao, Ftest> implements FtestService {

    public String getPostgisPoint( Point[][] point){
        StringBuilder pointStr = new StringBuilder("SRID=4326;MULTILINESTRING(");
        Arrays.stream(point).forEach(e->{
            pointStr.append("(");
            for (int i=0;i<e.length;i++){
                pointStr.append(e[i].getLat()+" ");
                pointStr.append(e[i].getLng());
                if (i!=e.length-1){
                    pointStr.append(",");
                }
            }
            pointStr.append("),");
        });
        pointStr.deleteCharAt(pointStr.length()-1);
        pointStr.append(")");
        return pointStr.toString();
    }

    @Override
    public void savePoint(Ftest entity) {
        Point[] point = entity.getPoints();
        String pointStr = "SRID=4326;Point("+point[0].getLat()+" "+point[0].getLng()+")";
        this.baseMapper.savePoint(entity.getId(),pointStr);
    }

    @Override
    public void savePoints(Ftest entity) {
        String pointStr = getPostgisPoint(entity.getLinePoints());
        log.info("-----------------"+pointStr+"----------------");
        this.baseMapper.savePoint(entity.getId(),pointStr);
    }

    @Override
    public Boolean updateEntityById(Ftest entity) {
        String pointStr = getPostgisPoint(entity.getLinePoints());
        return this.baseMapper.updateEntityById(entity.getId(),pointStr);
    }

    @Override
    public List<Ftest> listEntity() {
        List<Ftest> list = this.baseMapper.selectAll();
        list.stream().forEach(e->{
            e.setGeomObject(JSONObject.parseObject(e.getGeom()));
        });
        return list;
    }

    @Override
    public Ftest getEntityById(Integer id) {
        Ftest ftest =  this.baseMapper.getEntityById(id);
        ftest.setGeomObject(JSONObject.parseObject(ftest.getGeom()));
        return ftest;
    }

    @Override
    public List<Ftest> listEntityByIds(List<String> asList) {
        List<Ftest> list = this.baseMapper.listEntityByIds(asList);
        list.stream().forEach(e->{
            e.setGeomObject(JSONObject.parseObject(e.getGeom()));
        });
        return list;
    }

    @Override
    public PageInfo<Ftest> getPageInfo(int current, int pageSize) {
        PageHelper.startPage(current,pageSize);
        List<Ftest> list = this.baseMapper.selectAll();
        list.stream().forEach(e->{
            e.setGeomObject(JSONObject.parseObject(e.getGeom()));
        });
        return new PageInfo<>(list);
    }


}

xml文件:

<?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.cherry.manager.dao.FtestDao">

    <resultMap id="ftestMap" type="com.cherry.manager.entity.Ftest">
        <result property="id" column="id"/>
        <result property="geom" column="geom"/>
    </resultMap>

    <insert id="savePoint">
        insert into ftest(id,geom) values(#{id},#{points})
    </insert>

    <update id="updateEntityById">
        update ftest set geom = #{pointStr} where id = #{id};
    </update>

    <select id="selectAll" resultType="com.cherry.manager.entity.Ftest">
        select id, postgis.st_asgeojson(geom) as geom  from ftest
    </select>

    <select id="getEntityById" parameterType="integer" resultMap="ftestMap">
        select id, postgis.st_asgeojson(geom) as geom  from ftest where id = #{id}
    </select>

    <select id="listEntityByIds" parameterType="integer" resultMap="ftestMap">
        select id, postgis.st_asgeojson(geom) as geom from ftest
        <if test=" ids!=null ">
            <foreach collection="ids" open="where id in (" close=")" separator="," item="item">#{item}</foreach>
        </if>
        order by id
    </select>

    <select id="pageEntity" resultMap="ftestMap">
        select id, postgis.st_asgeojson(geom) as geom  from ftest
    </select>

</mapper>


相关文章:

  • linux内核移植流程
  • canvas 正在慢慢吃掉你的内存...
  • 【无标题】11111
  • go pprof 的使用
  • 类和对象 中
  • LeetCode变位词组
  • locust压测实例
  • 8.6 轻量化网络设计概述
  • 【C#】萌狼学习C#那年写的笔记汇总
  • 20个js工具函数助力高效开发
  • 软件领域中面向对象的设计模式
  • 01用户登录,登出,token等框架说明
  • 几位阿里发布这份内部MySQL性能优化法则笔记
  • java-php-python-ssm巢院小区疫情管控系统计算机毕业设计
  • Linux基础 - 系统安全(SELinux与Firewalld)
  • #Java异常处理
  • 【编码】-360实习笔试编程题(二)-2016.03.29
  • angular2开源库收集
  • canvas 高仿 Apple Watch 表盘
  • happypack两次报错的问题
  • Python 基础起步 (十) 什么叫函数?
  • 构建二叉树进行数值数组的去重及优化
  • 规范化安全开发 KOA 手脚架
  • 温故知新之javascript面向对象
  • 学习JavaScript数据结构与算法 — 树
  • 源码之下无秘密 ── 做最好的 Netty 源码分析教程
  • k8s使用glusterfs实现动态持久化存储
  • ​Spring Boot 分片上传文件
  • # 数据结构
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • #NOIP 2014#Day.2 T3 解方程
  • (13)Latex:基于ΤΕΧ的自动排版系统——写论文必备
  • (android 地图实战开发)3 在地图上显示当前位置和自定义银行位置
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (三)elasticsearch 源码之启动流程分析
  • (转) Android中ViewStub组件使用
  • (转)大道至简,职场上做人做事做管理
  • .net开发时的诡异问题,button的onclick事件无效
  • @column注解_MyBatis注解开发 -MyBatis(15)
  • @synthesize和@dynamic分别有什么作用?
  • [ HTML + CSS + Javascript ] 复盘尝试制作 2048 小游戏时遇到的问题
  • [C++] new和delete
  • [C++]运行时,如何确保一个对象是只读的
  • [Docker]四.Docker部署nodejs项目,部署Mysql,部署Redis,部署Mongodb
  • [E单调栈] lc2487. 从链表中移除节点(单调栈+递归+反转链表+多思路)
  • [HXPCTF 2021]includer‘s revenge
  • [IE9] 解决了傲游、搜狗浏览器在IE9下网页截图的问题
  • [LeetCode] Wildcard Matching
  • [linux][调度] 内核抢占入门 —— 高优先级线程被唤醒时会立即抢占当前线程吗 ?
  • [MicroPython]TPYBoard v102 CAN总线通信
  • [NOIP 2003] 栈(三种方法:DP、数论、搜索)
  • [OpenWrt]RAX3000一根线实现上网和看IPTV
  • [Pyhton]weakref 弱引用
  • [selenium] Handling Untrusted SSL certificate error in firefox
  • [SQL调优] Maclean讲SQL调优精要