java程序操作Geometry对象

Geometry 空间地理对象,Oracle中存储Geometry对象的字段类型是 MDSYS.SDO_GEOMETRY,在数据库中构建Geometry对象的方法:

v_pointarray  MDSYS.sdo_ordinate_array;
MDSYS.SDO_GEOMETRY(2003,
                 20131028,
                 null,
                 MDSYS.SDO_ELEM_INFO_ARRAY(1, 1003, 1),
                 v_pointarray);

其中 20131028是空间参考系。

在java程序中如何读写带有Geometry对象的表呢,常用的geotools工具包。在maven工程中引用jar包jts-1.13.jar

读取Geometry对象

在java映射的数据库表实体类对象的字段中添加Geometry类型,如下:

@Column(name = "GEOM")
private Geometry geom;

这样就能读取到Geometry 对象,Geometry 有很多空间计算方法,具体可以查看源码。

写入Geometry对象

相对于读取,写入就相对麻烦一些,首先要构建一个Geometry对象,分点线面的构建:

private GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

点的构建

Envelope e = new Envelope(new Coordinate(x, y));

线的构建

LineString line = geometryFactory.createLineString(Coordinate[]);

line.setSRID(20131028);
rb.setGeometry(line);

其中,rb实体类对象的Geometry的定义格式如下:

@Column(name = "PKG_CONVEX", jdbcType = JdbcType.STRUCT)
private Geometry geometry;

一定要指定jdbcType 类型,Oracle数据库中Geometry对象只接收STRUCT类型的数据。

 

可以使用JDBC连接mysql5.7,然后使用PreparedStatement对象Geometry数据写入到mysql5.7,具体步骤如下: 1. 加载JDBC驱动程序:Class.forName("com.mysql.jdbc.Driver"); 2. 连接mysql5.7数据库:Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); 3. 创建PreparedStatement对象:PreparedStatement ps = conn.prepareStatement("insert into table_name (geometry_column) values (?)"); 4. 将Geometry数据转换成byte数组:byte[] geometryBytes = geometry.toBinary(); 5. 将Geometry数据设置到PreparedStatement对象中:ps.setBytes(1, geometryBytes); 6. 执行插入操作:ps.executeUpdate(); 完整代码示例: ``` import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import com.vividsolutions.jts.geom.Geometry; public class GeometryToMysql { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "password"; try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, user, password); String sql = "insert into table_name (geometry_column) values (?)"; PreparedStatement ps = conn.prepareStatement(sql); // 将Geometry数据转换成byte数组 Geometry geometry = ...; byte[] geometryBytes = geometry.toBinary(); // 将Geometry数据设置到PreparedStatement对象中 ps.setBytes(1, geometryBytes); // 执行插入操作 ps.executeUpdate(); ps.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值