MySQL 并不支持自定义投影坐标系,所以如果用 ST_Distance() 来计算中国境内的两点距离,算出来的结果和真实距离的偏差大到基本不可用,所以需要使用空间函数的话,趁早放弃 MySQL 该用 PostGIS 。
Links
- Hibernate ORM Hibernate Spatial | MVNRepository
- MySQL Spatial Function Reference
安装
添加依赖:<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-spatial -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>5.4.10.Final</version>
</dependency>
配置
配置我们的断言:spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56InnoDBSpatialDialect
使用
首先我们在模型中添加需要的 Geometry 字段: ```java import org.locationtech.jts.geom.Point;
@Column(columnDefinition = “POINT”) private Point location;
测试:
```java
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
@Test
public void addTest() {
Point location = this.geometryFactory.createPoint(new Coordinate(113, 22));
UserDO userDO = new UserDO();
userDO.setEmail("liuzhaowei55@gmial.com");
userDO.setPassword("123456");
userDO.setNickname("Where");
userDO.setAvatar("https://static.moorper.com/avatar.png");
userDO.setLocation(location);
this.userRepository.save(userDO);
}