美文网首页
mybatis支持mysql的geometry类型字段

mybatis支持mysql的geometry类型字段

作者: 爱的旋转体 | 来源:发表于2020-05-11 16:02 被阅读0次

    1.自定义typehandler:

    package com.xzp.typehandler;
    
    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    import org.apache.ibatis.type.MappedJdbcTypes;
    import org.apache.ibatis.type.MappedTypes;
    import org.geolatte.geom.Geometry;
    import org.geolatte.geom.codec.Wkb;
    
    /**
     * 
     * @author xuzhipeng
     *
     */
    @SuppressWarnings("rawtypes")
    @MappedJdbcTypes(value = JdbcType.OTHER)
    @MappedTypes(value = {Geometry.class})
    public class GeometryTypeHandler extends BaseTypeHandler<Geometry>{
    
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType)
                throws SQLException {
        }
    
        @Override
        public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
            return fromMysqlWkb(rs.getBytes(columnName));
        }
    
        @Override
        public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            return fromMysqlWkb(rs.getBytes(columnIndex));
        }
    
        @Override
        public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
            return fromMysqlWkb(cs.getBytes(columnIndex));
        }
    
        private Geometry fromMysqlWkb(byte[] bytes) {
            if (bytes == null) {
                return null;
            }
            byte[] geomBytes = ByteBuffer.allocate(bytes.length - 4).order(ByteOrder.LITTLE_ENDIAN)
                    .put(bytes, 4, bytes.length - 4).array();
            return Wkb.fromWkb(org.geolatte.geom.ByteBuffer.from(geomBytes));
        }
    }
    

    2.springboot配置文件:

    mybatis:
            type-handlers-package: com.xzp.typehandler
    

    3.xml:

    <result column="location" property="location" typeHandler="com.xzp.typehandler.GeometryTypeHandler"/>
    

    参考:https://www.cnblogs.com/lookup/p/11523409.html

    相关文章

      网友评论

          本文标题:mybatis支持mysql的geometry类型字段

          本文链接:https://www.haomeiwen.com/subject/skwunhtx.html