本文实现过程是基于瀚高数据库 瀚高数据库里装了PostGis插件 这样才可以实现该操作。
请确保使用的数据库支持PostGIS或者装了PostGIS插件。
先在现有的表增加一个类型为 geometry(point,4326) 的字段。
alter table 表名 add 字段名 geometry(point,4326);
造一些假数据
INSERT INTO `dm_sample_point` (location, longitude, latitude) VALUES ('point(112.89763 9.54895)', '112.89763', '9.54895');
INSERT INTO `dm_sample_point` (location, longitude, latitude) VALUES ('point(113.89763 9.64895)', '113.89763', '9.64895');
INSERT INTO `dm_sample_point` (location, longitude, latitude) VALUES ('point(114.89763 9.74895)', '114.89763', '9.74895');
INSERT INTO `dm_sample_point` (location, longitude, latitude) VALUES ('point(115.89763 9.84895)', '115.89763', '9.84895');
location为点对象 坐标系为4326。
longitude是经度。
latitude是维度。
@Select({" <script> " +
" select * from 表名 test" +
" <where> " +
"test.island_id = #{id} " +
"<when test=\"locations !=null and locations.size>0\">" +
"and ST_CONTAINS(" +
"ST_TRANSFORM(ST_SetSRID(ST_GEOMFROMTEXT('POLYGON((" +
"<foreach item = 'item' collection = 'locations' index = 'index' separator = ','>" +
"${item.longitude} ${item.latitude}" +
"</foreach>" +
"))'), 4326), ST_SRID(test.location))," +
"test.location)" +
"</when>" +
"</where>" +
" </script> "})
该SQL是接收一个名为locations的List集合 集合里是对象 对象里是经度和维度两个字段。
在SQL中循环该集合中的值 通过PostGIS函数来形成多边形。
通过ST_CONTAINS函数来查询出 location 字段的经纬度是否在该多边形中。
ST_SetSRID是设置坐标系为4326 这一步必须 不然会报错。