背景
在做單車項(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