diff --git a/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java new file mode 100644 index 0000000000..977587a06a --- /dev/null +++ b/core-java/src/main/java/com/baeldung/array/ArrayBenchmarkRunner.java @@ -0,0 +1,21 @@ +package com.baeldung.array; + +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +public class ArrayBenchmarkRunner { + + public static void main(String[] args) throws Exception { + + Options options = new OptionsBuilder() + .include(SearchArrayTest.class.getSimpleName()).threads(1) + .forks(1).shouldFailOnError(true).shouldDoGC(true) + .jvmArgs("-server").build(); + + new Runner(options).run(); + + + } + +} diff --git a/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java similarity index 57% rename from core-java/src/test/java/com/baeldung/array/SearchArrayTest.java rename to core-java/src/main/java/com/baeldung/array/SearchArrayTest.java index 94911baac9..fd11e49373 100644 --- a/core-java/src/test/java/com/baeldung/array/SearchArrayTest.java +++ b/core-java/src/main/java/com/baeldung/array/SearchArrayTest.java @@ -1,78 +1,92 @@ package com.baeldung.array; -import org.junit.Test; +import org.openjdk.jmh.annotations.*; import java.util.*; +import java.util.concurrent.TimeUnit; public class SearchArrayTest { - - @Test - public void searchArrayAllocNewCollections() { + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @Warmup(iterations = 5) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + public void searchArrayLoop() { int count = 1000; - String[] strings = seedArray(count); + for (int i = 0; i < count; i++) { + searchLoop(strings, "T"); + } + } - long startTime = System.nanoTime(); + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @Warmup(iterations = 5) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + public void searchArrayAllocNewList() { + + int count = 1000; + String[] strings = seedArray(count); for (int i = 0; i < count; i++) { searchList(strings, "W"); } - long duration = System.nanoTime() - startTime; - System.out.println("SearchList: " + duration / 10000); - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - searchSet(strings,"S"); - } - duration = System.nanoTime() - startTime; - System.out.println("SearchSet: " + duration / 10000); - - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - searchLoop(strings, "T"); - } - duration = System.nanoTime() - startTime; - System.out.println("SearchLoop: " + duration / 10000); } - @Test - public void searchArrayReuseCollections() { + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @Warmup(iterations = 5) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + public void searchArrayAllocNewSet() { - int count = 10000; + int count = 1000; + String[] strings = seedArray(count); + for (int i = 0; i < count; i++) { + searchSet(strings, "S"); + } + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @Warmup(iterations = 5) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + public void searchArrayReuseList() { + + int count = 1000; String[] strings = seedArray(count); List asList = Arrays.asList(strings); - Set asSet = new HashSet<>(Arrays.asList(strings)); - long startTime = System.nanoTime(); for (int i = 0; i < count; i++) { asList.contains("W"); } - long duration = System.nanoTime() - startTime; - System.out.println("List: " + duration / 10000); - - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - asSet.contains("S"); - } - duration = System.nanoTime() - startTime; - System.out.println("Set: " + duration / 10000); - - startTime = System.nanoTime(); - for (int i = 0; i < count; i++) { - searchLoop(strings, "T"); - } - duration = System.nanoTime() - startTime; - System.out.println("Loop: " + duration / 10000); - } - @Test + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @Warmup(iterations = 5) + @OutputTimeUnit(TimeUnit.MICROSECONDS) + public void searchArrayReuseSet() { + + int count = 1000; + String[] strings = seedArray(count); + Set asSet = new HashSet<>(Arrays.asList(strings)); + for (int i = 0; i < count; i++) { + asSet.contains("S"); + } + } + + + @Benchmark + @BenchmarkMode(Mode.AverageTime) + @Warmup(iterations = 5) + @OutputTimeUnit(TimeUnit.MICROSECONDS) public void searchArrayBinarySearch() { - int count = 10000; + int count = 1000; String[] strings = seedArray(count); Arrays.sort(strings); @@ -81,7 +95,7 @@ public class SearchArrayTest { Arrays.binarySearch(strings, "A"); } long duration = System.nanoTime() - startTime; - System.out.println("Binary search: " + duration / 10000); + //System.out.println("Binary search: " + duration / 10000); } diff --git a/flyway/pom.xml b/flyway/pom.xml index 2774602654..5cb8fabe67 100644 --- a/flyway/pom.xml +++ b/flyway/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.baeldung flyway 1.0 flyway + pom A sample project to demonstrate Flyway migrations @@ -13,6 +13,10 @@ 1.0.0-SNAPSHOT + + spring-flyway + + mysql @@ -20,6 +24,17 @@ ${mysql.version} + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + @@ -32,5 +47,6 @@ 6.0.5 4.0.3 + 1.5.8.RELEASE \ No newline at end of file diff --git a/flyway/spring-flyway/.gitignore b/flyway/spring-flyway/.gitignore new file mode 100644 index 0000000000..2af7cefb0a --- /dev/null +++ b/flyway/spring-flyway/.gitignore @@ -0,0 +1,24 @@ +target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ \ No newline at end of file diff --git a/flyway/spring-flyway/pom.xml b/flyway/spring-flyway/pom.xml new file mode 100644 index 0000000000..cf5703cfab --- /dev/null +++ b/flyway/spring-flyway/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + spring-flyway + 0.0.1-SNAPSHOT + jar + + spring-flyway + Spring Boot Test Flyway Migrations + + + flyway + com.baeldung + 1.0 + ../../flyway + + + + UTF-8 + UTF-8 + 1.8 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.flywaydb + flyway-core + + + org.projectlombok + lombok + + + com.h2database + h2 + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/SpringFlywayApplication.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/SpringFlywayApplication.java new file mode 100644 index 0000000000..9218fbc88d --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/SpringFlywayApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springflyway; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringFlywayApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringFlywayApplication.class, args); + } +} diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/entities/Customer.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/entities/Customer.java new file mode 100644 index 0000000000..194b961d2d --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/entities/Customer.java @@ -0,0 +1,28 @@ +package com.baeldung.springflyway.entities; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class Customer { + + @Id + @GeneratedValue + private Long id; + + private String firstName; + private String lastName; + + private String email; + +} diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/migration/V2__uk_lastname_customer.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/migration/V2__uk_lastname_customer.java new file mode 100644 index 0000000000..52b851546b --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/migration/V2__uk_lastname_customer.java @@ -0,0 +1,14 @@ +package com.baeldung.springflyway.migration; + +import org.flywaydb.core.api.migration.spring.SpringJdbcMigration; +import org.springframework.jdbc.core.JdbcTemplate; + +public class V2__uk_lastname_customer implements SpringJdbcMigration { + + final String CUSTOMER_LASTNAME_UK = "ALTER TABLE customer ADD CONSTRAINT uk_customer_lastname UNIQUE(last_name);"; + + @Override + public void migrate(final JdbcTemplate jdbcTemplate) throws Exception { + jdbcTemplate.execute(CUSTOMER_LASTNAME_UK); + } +} diff --git a/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/repositories/CustomerRepository.java b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/repositories/CustomerRepository.java new file mode 100644 index 0000000000..0a1fb5a146 --- /dev/null +++ b/flyway/spring-flyway/src/main/java/com/baeldung/springflyway/repositories/CustomerRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.springflyway.repositories; + +import com.baeldung.springflyway.entities.Customer; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; + +public interface CustomerRepository extends JpaRepository { + + Optional findByEmail(String email); +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInitialMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInitialMigrationTest.java new file mode 100644 index 0000000000..b3f2cb29e1 --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInitialMigrationTest.java @@ -0,0 +1,28 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryInitialMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test + public void givenSchemaCreationMigration_whenTryingToCreateACustomer_thenSuccess() { + Customer customer = customerRepository.save(Customer + .builder() + .email("customer@email.com") + .build()); + assertNotNull(customer.getId()); + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInsertDataMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInsertDataMigrationTest.java new file mode 100644 index 0000000000..369e61d98f --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryInsertDataMigrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.*; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryInsertDataMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test + public void givenASetInsertData_whenRunningMigrationsWithSuccess_thenASpecificCustomerIsFound() { + Optional customerOptional = customerRepository.findByEmail("email@email.com"); + assertTrue(customerOptional.isPresent()); + } + + @Test + public void givenASetInsertData_whenRunningMigrationsWithSuccess_thenASetOfCustomersIsFound() { + List customers = customerRepository.findAll(); + assertNotNull(customers); + assertEquals(customers.size(), 6); + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryNotNullConstraintMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryNotNullConstraintMigrationTest.java new file mode 100644 index 0000000000..90517c9225 --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryNotNullConstraintMigrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryNotNullConstraintMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test(expected = DataIntegrityViolationException.class) + public void givenTheNotNullConstraintMigrations_whenInsertingACustomerWithNullEmail_thenThrowException() { + customerRepository.save(Customer + .builder() + .build()); + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintJavaMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintJavaMigrationTest.java new file mode 100644 index 0000000000..e5ba782fda --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintJavaMigrationTest.java @@ -0,0 +1,29 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(properties = { + "flyway.locations[0]=db/migration", "flyway.locations[1]=com/baeldung/springflyway/migration" +}) +public class CustomerRepositoryUniqueConstraintJavaMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test(expected = DataIntegrityViolationException.class) + public void givenTheUniqueConstraintMigrations_whenInsertingAnExistingLastNameCustomer_thenThrowException() { + customerRepository.save(Customer + .builder() + .lastName("LastName") + .build()); + + } + +} diff --git a/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintMigrationTest.java b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintMigrationTest.java new file mode 100644 index 0000000000..9fa2dee42d --- /dev/null +++ b/flyway/spring-flyway/src/test/java/com/baeldung/springflyway/CustomerRepositoryUniqueConstraintMigrationTest.java @@ -0,0 +1,27 @@ +package com.baeldung.springflyway; + +import com.baeldung.springflyway.entities.Customer; +import com.baeldung.springflyway.repositories.CustomerRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class CustomerRepositoryUniqueConstraintMigrationTest { + + @Autowired CustomerRepository customerRepository; + + @Test(expected = DataIntegrityViolationException.class) + public void givenTheUniqueConstraintMigrations_whenInsertingAnExistingEmailCustomer_thenThrowException() { + customerRepository.save(Customer + .builder() + .email("email@email.com") + .build()); + + } + +} diff --git a/flyway/spring-flyway/src/test/resources/application.properties b/flyway/spring-flyway/src/test/resources/application.properties new file mode 100644 index 0000000000..5656ca79ce --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.jpa.hibernate.ddl-auto=validate \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_0__create_table_customer.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_0__create_table_customer.sql new file mode 100644 index 0000000000..8c65253ed8 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_0__create_table_customer.sql @@ -0,0 +1,6 @@ +create table if not exists customer ( + id bigint AUTO_INCREMENT not null primary key, + first_name varchar(255) , + last_name varchar(255) , + email varchar(255) +); \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_1__insert_customer.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_1__insert_customer.sql new file mode 100644 index 0000000000..6bba6e00a1 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_1__insert_customer.sql @@ -0,0 +1,6 @@ +insert into customer (first_name, last_name, email) values ('FirstName', 'LastName', 'email@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName1', 'LastName1', 'email1@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName2', 'LastName2', 'email2@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName3', 'LastName3', 'email3@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName4', 'LastName4', 'email4@email.com'); +insert into customer (first_name, last_name, email) values ('FirstName5', 'LastName5', 'email5@email.com'); \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_2__make_email_not_null.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_2__make_email_not_null.sql new file mode 100644 index 0000000000..b1cc396741 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_2__make_email_not_null.sql @@ -0,0 +1 @@ +ALTER TABLE customer ALTER email SET NOT NULL; \ No newline at end of file diff --git a/flyway/spring-flyway/src/test/resources/db/migration/V1_3__make_email_unique.sql b/flyway/spring-flyway/src/test/resources/db/migration/V1_3__make_email_unique.sql new file mode 100644 index 0000000000..19d738fe46 --- /dev/null +++ b/flyway/spring-flyway/src/test/resources/db/migration/V1_3__make_email_unique.sql @@ -0,0 +1 @@ +ALTER TABLE customer ADD CONSTRAINT uk_customer_email UNIQUE(email); \ No newline at end of file diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java index f1fc22d29a..25fc0d7b02 100644 --- a/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java +++ b/hibernate5/src/main/java/com/baeldung/hibernate/HibernateUtil.java @@ -6,6 +6,7 @@ import com.baeldung.hibernate.pojo.OrderEntry; import com.baeldung.hibernate.pojo.OrderEntryIdClass; import com.baeldung.hibernate.pojo.OrderEntryPK; import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; import com.baeldung.hibernate.pojo.Product; import com.baeldung.hibernate.pojo.Phone; import com.baeldung.hibernate.pojo.TemporalValues; @@ -79,6 +80,7 @@ public class HibernateUtil { metadataSources.addAnnotatedClass(Car.class); metadataSources.addAnnotatedClass(Bag.class); metadataSources.addAnnotatedClass(PointEntity.class); + metadataSources.addAnnotatedClass(PolygonEntity.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder() diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java new file mode 100644 index 0000000000..69208c8cd4 --- /dev/null +++ b/hibernate5/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.pojo; + +import com.vividsolutions.jts.geom.Polygon; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class PolygonEntity { + + @Id + @GeneratedValue + private Long id; + + private Polygon polygon; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Polygon getPolygon() { + return polygon; + } + + public void setPolygon(Polygon polygon) { + this.polygon = polygon; + } + + @Override + public String toString() { + return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}'; + } +} diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java index a5c7b329fc..10b5cbef4e 100644 --- a/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java +++ b/hibernate5/src/test/java/com/baeldung/hibernate/HibernateSpatialTest.java @@ -1,10 +1,14 @@ package com.baeldung.hibernate; import com.baeldung.hibernate.pojo.PointEntity; +import com.baeldung.hibernate.pojo.PolygonEntity; +import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; +import com.vividsolutions.jts.util.GeometricShapeFactory; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.After; @@ -13,6 +17,7 @@ import org.junit.Test; import javax.persistence.Query; import java.io.IOException; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; @@ -82,16 +87,58 @@ public class HibernateSpatialTest { .containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)"); } + @Test + public void shouldSelectAllPointsWithinRadius() throws ParseException { + insertPoint("POINT (1 1)"); + insertPoint("POINT (1 2)"); + insertPoint("POINT (3 4)"); + insertPoint("POINT (5 6)"); + + Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true", + PointEntity.class); + query.setParameter("circle", createCircle(0.0, 0.0, 5)); + + assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString())) + .containsOnly("POINT (1 1)", "POINT (1 2)"); + } + + @Test + public void shouldSelectAdjacentPolygons() throws ParseException { + insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))"); + insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))"); + + Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true", + PolygonEntity.class); + query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))")); + assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString())) + .containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))"); + } + private void insertPoint(String point) throws ParseException { PointEntity entity = new PointEntity(); entity.setPoint((Point) wktToGeometry(point)); session.persist(entity); } + private void insertPolygon(String polygon) throws ParseException { + PolygonEntity entity = new PolygonEntity(); + entity.setPolygon((Polygon) wktToGeometry(polygon)); + session.persist(entity); + } + private Geometry wktToGeometry(String wellKnownText) throws ParseException { WKTReader fromText = new WKTReader(); Geometry geom = null; geom = fromText.read(wellKnownText); return geom; } + + private static Geometry createCircle(double x, double y, double radius) { + GeometricShapeFactory shapeFactory = new GeometricShapeFactory(); + shapeFactory.setNumPoints(32); + shapeFactory.setCentre(new Coordinate(x, y)); + shapeFactory.setSize(radius * 2); + return shapeFactory.createCircle(); + } }