Spring Data JPA
The extremely easy way to use JPA
. Spring Data JPA
Introduced hibernate-spatial
to remove heterogeneity in database support. In this example, the use of , , and together
is integrated .Spring Data JPA
hibernate -spatial
PostGIS
1. Add dependencies
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>5.2.10.Final</version>
</dependency>
2. Database dialect specification
spring.jpa.database-platform: org.hibernate.spatial.dialect.postgis.PostgisPG9Dialect
org.hibernate.spatial.dialect
There are also dialects of h2
, mysql
, oracle
, below.sqlserver
3. Attribute Mapping
@Column(columnDefinition = "geometry(Point,4326)")
private Point point;
4. Define the Spring Data Repository
public interface CityRepository extends JpaRepository<City,Long> {
@Query("select city from City as city where equals(city.point,:point) = TRUE")
List<City> findByPoint(@Param("point") Point point);
}
5. Save the test
@Bean
CommandLineRunner geometrySave(CityRepository cityRepository){
return e ->{
City city = new City();
city.setName("合肥");
Geometry point = wktReader().read("POINT (117.2 31.8)");
Point pointToSave = point.getInteriorPoint();
pointToSave.setSRID(4326);
city.setPoint(pointToSave);
cityRepository.save(city);
};
}
6. Read Test
@Bean
CommandLineRunner geometryRead(CityRepository cityRepository){
return e -> {
City city = cityRepository.findOne(3l);
Point point = city.getPoint();
log.info("经度:" + point.getX() + " 维度:" + point.getY() + " 坐标系统:" + point.getSRID());
};
}
7. Query test
@Bean
CommandLineRunner geometryQuery(CityRepository cityRepository){
return e -> {
Geometry point = wktReader().read("POINT (117.2 31.8)");
Point pointToQuery = point.getInteriorPoint();
pointToQuery.setSRID(4326);
List<City> cities = cityRepository.findByPoint(pointToQuery);
for (City city : cities) {
log.info("查询结果为:" + city.getId() + "/" +city.getName() + "/" +city.getPoint());
}
};
}
We cityRepository
use the hibernate-spatial
spatial function equals
in , please see
http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#spatial-configuration-dialect for a list of spatial functions
8 Source address
http://www.wisely.top/2017/06/26/hibernate-spatial-spring-data-jpa/