如何使用mybatis在java中映射mysql点类型?现在是java.lang.Object。 这是我的表:
CREATE TABLE `test` (
`id` int(11) NOT NULL,
`location` point DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
这是生成器提供的xml:
<resultMap id="BaseResultMap" type="package.model.Test">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="location" jdbcType="OTHER" property="location" />
</resultMap>
<insert id="insert" parameterType="package.model.Test">
insert into test (id, location)
values (#{id,jdbcType=INTEGER}, #{location,jdbcType=OTHER})
</insert>
我试过了:
public void testPointType() {
GeometryFactory geometryFactory = new GeometryFactory();
com.vividsolutions.jts.geom.Point point = geometryFactory.createPoint(new Coordinate(1, 1));
package.model.Test record = new package.model.Test();
record.setLocation(point.toText());
testMapper.insertSelective(record);
}
但是得到:com.mysql.jdbc.MysqlDataTruncation: Data truncation: Cannot get geometry object from data you send to the GEOMETRY field
答案 0 :(得分:1)
经过几个小时的挖掘。我一直在寻找这种方式:
<insert id="insert" parameterType="package.model.Test">
insert into test (id, location)
values (#{id,jdbcType=INTEGER}, GeomFromText(#{location,jdbcType=OTHER}))
</insert>
并且在java中,模型可以将点类型作为Object,并赋值为String&#34; point(1 1)&#34;或使用vividsolutions geometryObject.toText()
方法。
在开始时没有工作是因为,如果没有GeomFromText()
,mybatis将其视为insert int test (id, location) values (1, 'point(1 1)')
,则会围绕该值引用。
选择:
<select resultType="java.lang.String">
select astext(location) from test
</select>
答案 1 :(得分:0)
不确定模型Test
中的字段是什么,并且不确定它是否适合您,但只是尝试一下;)
<insert id="insert" parameterType="package.model.Test">
insert into test (id, location)
values (#{id,jdbcType=INTEGER}, Point( #{location.x}, #{location.x} ))
</insert>
我认为您最好定义模型Test
,如:
public class Test {
private String id;
private String locationX;
private String locationY;
... ...
getter and setter
... ...
}
然后你可以这样做:
<insert id="insert" parameterType="package.model.Test">
insert into test (id, location)
values (#{id,jdbcType=INTEGER}, Point( #{locationX}, #{locationY} ))
</insert>
对于此类型Test
,您可以执行select
之类的操作:
<select id="insert" resultType="package.model.Test">
select id, x(location) as locationX, y(location) as locationY from test
</select>