讓你的spring data jpa支持mysql的空間存儲(chǔ)

背景

在做單車項(xiàng)目的時(shí)候,有一個(gè)功能點(diǎn)是展示周圍的車輛。其實(shí)這個(gè)功能在之前的項(xiàng)目中也用到過,只不過一直都是用的mongoDB來實(shí)現(xiàn)的,后來在看文檔的時(shí)候發(fā)現(xiàn)了,mysql也支持就想嘗試使用下,在使用的過程中,出現(xiàn)了許多障礙,特此記錄下。

一、 首先創(chuàng)建表,索引。

CREATE TABLE location(  
  
   address CHAR(80) NOT NULL,  
  
   address_loc POINT NOT NULL,  
  
   PRIMARY KEY(address)  
  
); 

ALTER TABLE address ADD SPATIAL INDEX(address_loc);  

二、 使用springboot創(chuàng)建數(shù)據(jù)層

1. 創(chuàng)建entity

  @Entity
  @Table(name = "location")
  public class LocationEntity implements java.io.Serializable {
  /**  */
    @Column(name = "address", unique = true, nullable = false, length = 80)
    private String address;

    /** 此處Point(緯度,經(jīng)度) */
    @Column(name = "address_loc",columnDefinition = "POINT")
    private Point addressLoc;
}

2. jpa

    public interface LocationDao  extends JpaRepository<LocationEntity , Integer>{}

三、service處理

@Override
public Result pushRedPackage(LocationEntity entity) {
    
    //TODO 處理一些業(yè)務(wù)判斷
        ……

    WKTReader reader = new WKTReader();
    Geometry geom = null;
    try {
        geom = reader.read("POINT(" + entity.getLat() + " " + entity.getLon() + ")");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    entity.setAddress((com.vividsolutions.jts.geom.Point) geom);
    redDao.save(entity);
    return Result.ok();
}

關(guān)鍵點(diǎn)留在最后,這樣還不足以能插入數(shù)據(jù),會(huì)提示異常。Cannot get geometry object from data you send to the GEOMETRY field

需要在配置文件jpa加入支持。我使用的yml文件。

jpa:
   show-sql: true
   hibernate:
     naming:
       physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
   properties:
     hibernate.format_sql: true
     hibernate.dialect: org.hibernate.spatial.dialect.mysql.MySQL56InnoDBSpatialDialect
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容