Can not resolve 'ST_GeomFromText' in serviceImpl class.
I am trying to save my geometry data to mysql table through JPA.
georepository.save("id", ST_GeomFromText('POLYGON((0 1, 2 5, 2 7, 0 7, 0 1))') );
but I am getting Can not resolve 'ST_GeomFromText' in serviceImpl class.
here is my model
public class Mygeo {
@Id
@Column(name = "id")
private String id;
@Column(name = "geodata", nullable = false)
private Geometry geodata;
}
This is how I am saving manually in DB. what will be the JPA alternate way to save this.
INSERT INTO mygeo (id, geodata)VALUES ("ID",ST_GeomFromText('POLYGON((0 1, 2 5, 2 7, 0 7, 0 1))'));
Note : I do have access of geometry string like this
System.out.println(geometryObject.toString());
{"coordinates":[[[0,1],[2,5],[2,7],[0,7],[0,1]]],"type":"Polygon"}
CodePudding user response:
The way to save the Geometry data into database while using the Spring Data JPA is given below in details (step - by - step):
I will explain with the help of a project.
The project structure :
MyGeo entity :
package com.solve.problemssolve;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.locationtech.jts.geom.Geometry;
import lombok.Data;
@Data
@Entity
public class MyGeo {
@Id
@Column(name = "id")
private String id;
@Column(name = "geodata", nullable = false)
private Geometry geodata;
}
MyGeoRepository class
package com.solve.problemssolve;
import org.springframework.data.jpa.repository.JpaRepository;
public interface MyGeoRepository extends JpaRepository<MyGeo, String> {
}
application.properties :
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=Anish@123
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL5SpatialDialect
Note: You have to enable org.hibernate.spatial.dialect.mysql.MySQL5SpatialDialect
in your spring boot application to support spatial features.
Note: This table is automatically generated by Hibernate as I have kept ddl-auto=update
but you can create table manually also.
Resource class :
@RestController
public class Resource {
@Autowired
private MyGeoRepository myGeoRepository;
@GetMapping("/save")
public void save() throws ParseException {
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read("POLYGON((0 1, 2 5, 2 7, 0 7, 0 1))");
System.out.println(geometry);
MyGeo geo = new MyGeo();
geo.setGeodata(geometry);
geo.setId("ID");
myGeoRepository.save(geo);
System.out.println(myGeoRepository.findById("ID"));
}
}
You have to use WKTReader
to save the data via JPA.
DB row screenshot :