Skip to content

Instantly share code, notes, and snippets.

@michael-simons
Last active October 19, 2020 16:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save michael-simons/824ff17aebc1aa6fe4cf26a3fe795892 to your computer and use it in GitHub Desktop.
Save michael-simons/824ff17aebc1aa6fe4cf26a3fe795892 to your computer and use it in GitHub Desktop.
An example on how to use Hibernate-Spatial with Spring Data JPA Repositories
@Entity
@Table(name = "things")
public class ThingEntity {
@Id
private Long id;
// Needed for use with Hibernate Spatial 4.x
// @Type(type = "org.hibernate.spatial.GeometryType")
private Geometry geometry;
}
import org.springframework.data.repository.Repository;
import org.springframework.data.jpa.repository.Query;
public interface ThingRepository extends Repository<ThingEntity, Long> {
// This is a JPQL Query. Take note how I referenced the name of the entity, it's a Spring EL variable
// If you refactor your entity, its name will be taken care of...
@Query(value
= "Select t from #{#entityName} t"
+ " where intersects(t.geometry, :area) = true"
)
List<ThingEntity> findWithinArea(Geometry area);
}
@thinkyard
Copy link

I'm getting Caused by: org.postgresql.util.PSQLException: ERROR: function st_within(public.geometry, bytea) does not exist exception while executing:

@Query(value
            = "select t from Media t"
            + " where within(t.location, :circle) = true"
            + " order by t.captureDate desc"
    )
    List<Media> findWithinRadius(@Param("circle") Geometry circle);

A possible solution I found is to run SET search_path TO my_schema, public; on PostgreSQL but no help. Do you have any idea about this?

@russellhoff
Copy link

As stated in Repository Query Keywords on Spring Data JPA documentation, there are two of them that could be used as spatial queries: Within and Containing.

Unfortunately they're not working. What I've written and it's also working is:

public interface IMunicipioRepository extends CrudRepository<Municipio, Integer> {

	Optional<Municipio> findTopByTextoLikeOrderByTexto(String texto);
	@Query("FROM Municipio m WHERE CONTAINS(m.geom, :point) = true")
	Optional<Municipio> findMunicipioContainingPoint(Point point);
	
}

@ctimmins
Copy link

ctimmins commented Feb 6, 2018

@thinkyard the issue is there is no postgis function that supports comparing a geometry and a byte array (bytea). Try casting the byte array to a geom. also double check that function exists on the database

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment