JTS:05 MyBatis 数据转换类TypeHandler

版本

org.locationtech.jts:jts-core:1.19.0
链接: github

代码

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKBReader;
import org.locationtech.jts.io.WKBWriter;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JTS.Geometry 转换 
 * @author Lihan
 * @since 2021年11月15日 10:48:55
 */
@MappedTypes(value = {Geometry.class})
public class JTSGeometryTypeHandler extends BaseTypeHandler<Geometry> {
	
	private final WKBReader wkbReader = new WKBReader();
	private final WKBWriter wkbWriter = new WKBWriter();

	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setBytes(i, wkbWriter.write(parameter));
	}

	@Override
	public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
		try {
			return wkbReader.read(WKBReader.hexToBytes(rs.getString(columnName)));
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		try {
			return wkbReader.read(WKBReader.hexToBytes(rs.getString(columnIndex)));
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		try {
			return wkbReader.read(WKBReader.hexToBytes(cs.getString(columnIndex)));
		} catch (Exception e) {
			return null;
		}
	}
}

Mybatis-Plus 配置

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> {
        	TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            typeHandlerRegistry.register(PGgeometry.class, new GeometryTypeHandler());
            typeHandlerRegistry.register(Geometry.class, new JTSGeometryTypeHandler());
        };
    }

你可能感兴趣的:(JTS,mybatis,JTS)