From 566d7957592c40fcb28bd98484e6c8eec759382c Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Fri, 5 Jun 2020 23:56:54 +0530 Subject: [PATCH 001/155] Added code to access private properties of a class --- .../AccessPrivateProperties.java | 27 ++++++++++++ .../access/privatefields/Person.java | 18 ++++++++ .../AccessPrivateFieldsUnitTest.java | 36 ++++++++++++++++ .../AccessPrivateMethodsUnitTest.java | 43 +++++++++++++++++++ 4 files changed, 124 insertions(+) create mode 100755 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java create mode 100755 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java create mode 100644 core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java create mode 100644 core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java new file mode 100755 index 0000000000..938f5fd4a2 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java @@ -0,0 +1,27 @@ +package com.baeldung.reflection.access.privatefields; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class AccessPrivateProperties { + + public void accessPrivateFields(String declaredField, Object declaredFieldValue, boolean accessible) throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + Person person = new Person(); + Field field = person.getClass() + .getDeclaredField(declaredField); + field.setAccessible(accessible); + field.set(person, declaredFieldValue); + System.out.println(person.getName()); + } + + public void accessPrivateMethods(String declaredMethod, Class parameterType, Object name, boolean accessible) throws NoSuchMethodException, IllegalAccessException, NullPointerException, IllegalArgumentException, InvocationTargetException { + Person person = new Person(); + Method method = person.getClass() + .getDeclaredMethod(declaredMethod, parameterType); + method.setAccessible(accessible); + String greetMessage = (String) method.invoke(person, name); + System.out.println(greetMessage); + } + +} diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java new file mode 100755 index 0000000000..e59ff3bea8 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java @@ -0,0 +1,18 @@ +package com.baeldung.reflection.access.privatefields; + +public class Person { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + private String greet(String number) { + return "Hi " + Integer.parseInt(number); + } +} diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java new file mode 100644 index 0000000000..8faea06f78 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -0,0 +1,36 @@ +package com.baeldung.reflection.access.privatefields; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +public class AccessPrivateFieldsUnitTest { + + private static AccessPrivateProperties accessPrivateProperties; + + @BeforeAll + public static void beforeAll() { + accessPrivateProperties = new AccessPrivateProperties(); + } + + @Test + public void testForNoSuchFieldException() { + Assertions.assertThrows(NoSuchFieldException.class, () -> accessPrivateProperties.accessPrivateFields("firstName", "John", true)); + } + + @Test + public void testForIllegalAccessException() { + Assertions.assertThrows(IllegalAccessException.class, () -> accessPrivateProperties.accessPrivateFields("name", "John", false)); + } + + @Test + public void testForIllegalArgumentException() { + Assertions.assertThrows(IllegalArgumentException.class, () -> accessPrivateProperties.accessPrivateFields("name", 25, true)); + } + + @Test + public void testForNullPointerException() { + Assertions.assertThrows(NullPointerException.class, () -> accessPrivateProperties.accessPrivateFields(null, "John", true)); + } + +} diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java new file mode 100644 index 0000000000..a2e0f3fe28 --- /dev/null +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java @@ -0,0 +1,43 @@ +package com.baeldung.reflection.access.privatefields; + +import java.lang.reflect.InvocationTargetException; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +public class AccessPrivateMethodsUnitTest { + + private static AccessPrivateProperties accessPrivateProperties; + + @BeforeAll + public static void beforeAll() { + accessPrivateProperties = new AccessPrivateProperties(); + } + + @Test + public void testForNoSuchMethodException() { + Assertions.assertThrows(NoSuchMethodException.class, () -> accessPrivateProperties.accessPrivateMethods("greeting", String.class, "5", true)); + } + + @Test + public void testForIllegalAccessException() { + Assertions.assertThrows(IllegalAccessException.class, () -> accessPrivateProperties.accessPrivateMethods("greet", String.class, "5", false)); + } + + @Test + public void testForIllegalArgumentException() { + Assertions.assertThrows(IllegalArgumentException.class, () -> accessPrivateProperties.accessPrivateMethods("greet", String.class, 5, true)); + } + + @Test + public void testForNullPointerException() { + Assertions.assertThrows(NullPointerException.class, () -> accessPrivateProperties.accessPrivateMethods(null, String.class, "5", true)); + } + + @Test + public void testForInvocationTargetException() { + Assertions.assertThrows(InvocationTargetException.class, () -> accessPrivateProperties.accessPrivateMethods("greet", String.class, "John", true)); + } + +} From ba3bd78a108fae20e98049aa2a015a95c26119ce Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Wed, 10 Jun 2020 23:23:29 +0530 Subject: [PATCH 002/155] Removed abstractions to increase simplicity. --- .../AccessPrivateProperties.java | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100755 core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java deleted file mode 100755 index 938f5fd4a2..0000000000 --- a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/AccessPrivateProperties.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.reflection.access.privatefields; - -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class AccessPrivateProperties { - - public void accessPrivateFields(String declaredField, Object declaredFieldValue, boolean accessible) throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { - Person person = new Person(); - Field field = person.getClass() - .getDeclaredField(declaredField); - field.setAccessible(accessible); - field.set(person, declaredFieldValue); - System.out.println(person.getName()); - } - - public void accessPrivateMethods(String declaredMethod, Class parameterType, Object name, boolean accessible) throws NoSuchMethodException, IllegalAccessException, NullPointerException, IllegalArgumentException, InvocationTargetException { - Person person = new Person(); - Method method = person.getClass() - .getDeclaredMethod(declaredMethod, parameterType); - method.setAccessible(accessible); - String greetMessage = (String) method.invoke(person, name); - System.out.println(greetMessage); - } - -} From 8e2725a64e604c7add45ca58203626a7238f9618 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Wed, 10 Jun 2020 23:27:42 +0530 Subject: [PATCH 003/155] Added unit test cases in givenX_whenY_thenZ format. --- .../access/privatefields/Person.java | 11 ++-- .../AccessPrivateFieldsUnitTest.java | 43 +++++++++------- .../AccessPrivateMethodsUnitTest.java | 51 ++++++++++++------- 3 files changed, 65 insertions(+), 40 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java index e59ff3bea8..199d2429a7 100755 --- a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java @@ -1,7 +1,7 @@ package com.baeldung.reflection.access.privatefields; public class Person { - + private String name; public String getName() { @@ -12,7 +12,12 @@ public class Person { this.name = name; } - private String greet(String number) { - return "Hi " + Integer.parseInt(number); + private String greet(String name) { + return "Hello " + name; } + + private int divideByZeroExample() { + return 1 / 0; + } + } diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index 8faea06f78..200ccea9e3 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -1,36 +1,43 @@ package com.baeldung.reflection.access.privatefields; +import java.lang.reflect.Field; + import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class AccessPrivateFieldsUnitTest { - private static AccessPrivateProperties accessPrivateProperties; + @Test + public void whenGetField_thenSuccess() throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + Person person = new Person(); + person.setName("John"); - @BeforeAll - public static void beforeAll() { - accessPrivateProperties = new AccessPrivateProperties(); + Field field = person.getClass() + .getDeclaredField("name"); + field.setAccessible(true); + + String name = (String) field.get(person); + + Assertions.assertEquals("John", name); } @Test - public void testForNoSuchFieldException() { - Assertions.assertThrows(NoSuchFieldException.class, () -> accessPrivateProperties.accessPrivateFields("firstName", "John", true)); + public void givenInt_whenSetStringField_thenIllegalArgumentException() throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + Person person = new Person(); + Field field = person.getClass() + .getDeclaredField("name"); + field.setAccessible(true); + + Assertions.assertThrows(IllegalArgumentException.class, () -> field.setInt(person, 25)); } @Test - public void testForIllegalAccessException() { - Assertions.assertThrows(IllegalAccessException.class, () -> accessPrivateProperties.accessPrivateFields("name", "John", false)); - } + public void whenFieldNotSetAccessible_thenIllegalAccessException() throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + Person person = new Person(); + Field field = person.getClass() + .getDeclaredField("name"); - @Test - public void testForIllegalArgumentException() { - Assertions.assertThrows(IllegalArgumentException.class, () -> accessPrivateProperties.accessPrivateFields("name", 25, true)); - } - - @Test - public void testForNullPointerException() { - Assertions.assertThrows(NullPointerException.class, () -> accessPrivateProperties.accessPrivateFields(null, "John", true)); + Assertions.assertThrows(IllegalAccessException.class, () -> field.set(person, "John")); } } diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java index a2e0f3fe28..b44731c7ef 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java @@ -1,43 +1,56 @@ package com.baeldung.reflection.access.privatefields; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class AccessPrivateMethodsUnitTest { - private static AccessPrivateProperties accessPrivateProperties; + @Test + public void whenGetMethod_thenSuccess() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Person person = new Person(); - @BeforeAll - public static void beforeAll() { - accessPrivateProperties = new AccessPrivateProperties(); + Method method = person.getClass() + .getDeclaredMethod("greet", String.class); + method.setAccessible(true); + + String greetMessage = (String) method.invoke(person, "John"); + + Assertions.assertEquals("Hello John", greetMessage); } @Test - public void testForNoSuchMethodException() { - Assertions.assertThrows(NoSuchMethodException.class, () -> accessPrivateProperties.accessPrivateMethods("greeting", String.class, "5", true)); + public void givenInt_whenInvokeMethod_thenIllegalArgumentException() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Person person = new Person(); + + Method method = person.getClass() + .getDeclaredMethod("greet", String.class); + method.setAccessible(true); + + Assertions.assertThrows(IllegalArgumentException.class, () -> method.invoke(person, 25)); } @Test - public void testForIllegalAccessException() { - Assertions.assertThrows(IllegalAccessException.class, () -> accessPrivateProperties.accessPrivateMethods("greet", String.class, "5", false)); + public void whenMethodNotSetAccessible_thenIllegalAccessException() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Person person = new Person(); + + Method method = person.getClass() + .getDeclaredMethod("greet", String.class); + + Assertions.assertThrows(IllegalAccessException.class, () -> method.invoke(person, "John")); } @Test - public void testForIllegalArgumentException() { - Assertions.assertThrows(IllegalArgumentException.class, () -> accessPrivateProperties.accessPrivateMethods("greet", String.class, 5, true)); - } + public void whenCallingMethodThrowsException_thenInvocationTargetException() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Person person = new Person(); - @Test - public void testForNullPointerException() { - Assertions.assertThrows(NullPointerException.class, () -> accessPrivateProperties.accessPrivateMethods(null, String.class, "5", true)); - } + Method method = person.getClass() + .getDeclaredMethod("divideByZeroExample"); + method.setAccessible(true); - @Test - public void testForInvocationTargetException() { - Assertions.assertThrows(InvocationTargetException.class, () -> accessPrivateProperties.accessPrivateMethods("greet", String.class, "John", true)); + Assertions.assertThrows(InvocationTargetException.class, () -> method.invoke(person)); } } From f72691730627f9b54bf3ef38a516bff5643a250b Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Mon, 15 Jun 2020 23:32:09 +0530 Subject: [PATCH 004/155] Included test cases for NoSuchFieldException, NoSuchMethodException and NullPointerException. --- .../access/privatefields/Person.java | 12 ++++- .../AccessPrivateFieldsUnitTest.java | 46 ++++++++++++++----- .../AccessPrivateMethodsUnitTest.java | 32 +++++++++---- 3 files changed, 68 insertions(+), 22 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java index 199d2429a7..2ec263f6ae 100755 --- a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java @@ -2,7 +2,9 @@ package com.baeldung.reflection.access.privatefields; public class Person { - private String name; + private String name = "John"; + + private int age = 30; public String getName() { return name; @@ -12,6 +14,14 @@ public class Person { this.name = name; } + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + private String greet(String name) { return "Hello " + name; } diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index 200ccea9e3..b885e3b669 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -8,36 +8,58 @@ import org.junit.jupiter.api.Test; public class AccessPrivateFieldsUnitTest { @Test - public void whenGetField_thenSuccess() throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + public void whenGetFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - person.setName("John"); - Field field = person.getClass() + Field fieldName = person.getClass() .getDeclaredField("name"); - field.setAccessible(true); + fieldName.setAccessible(true); - String name = (String) field.get(person); + String name = (String) fieldName.get(person); + + Field fieldAge = person.getClass() + .getDeclaredField("age"); + fieldAge.setAccessible(true); + + int age = fieldAge.getInt(person); Assertions.assertEquals("John", name); + Assertions.assertEquals(30, age); } @Test - public void givenInt_whenSetStringField_thenIllegalArgumentException() throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + public void givenInt_whenSetStringField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - Field field = person.getClass() + Field fieldName = person.getClass() .getDeclaredField("name"); - field.setAccessible(true); + fieldName.setAccessible(true); - Assertions.assertThrows(IllegalArgumentException.class, () -> field.setInt(person, 25)); + Assertions.assertThrows(IllegalArgumentException.class, () -> fieldName.setInt(person, 25)); } @Test - public void whenFieldNotSetAccessible_thenIllegalAccessException() throws NoSuchFieldException, NullPointerException, IllegalArgumentException, IllegalAccessException { + public void whenFieldNotSetAccessible_thenIllegalAccessException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - Field field = person.getClass() + Field fieldName = person.getClass() .getDeclaredField("name"); - Assertions.assertThrows(IllegalAccessException.class, () -> field.set(person, "John")); + Assertions.assertThrows(IllegalAccessException.class, () -> fieldName.get(person)); + } + + @Test + public void whenAccessingWrongProperty_thenNoSuchFieldException() throws NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass() + .getDeclaredField("genders")); + } + + @Test + public void whenAccessingNullProperty_thenNullPointerException() throws NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Assertions.assertThrows(NullPointerException.class, () -> person.getClass() + .getDeclaredField(null)); } } diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java index b44731c7ef..10c953f4af 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java @@ -9,20 +9,20 @@ import org.junit.jupiter.api.Test; public class AccessPrivateMethodsUnitTest { @Test - public void whenGetMethod_thenSuccess() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + public void whenGetMethod_thenSuccess() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NullPointerException { Person person = new Person(); Method method = person.getClass() .getDeclaredMethod("greet", String.class); method.setAccessible(true); - String greetMessage = (String) method.invoke(person, "John"); + String greetMessage = (String) method.invoke(person, "Jane"); - Assertions.assertEquals("Hello John", greetMessage); + Assertions.assertEquals("Hello Jane", greetMessage); } @Test - public void givenInt_whenInvokeMethod_thenIllegalArgumentException() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + public void givenInt_whenInvokeMethod_thenIllegalArgumentException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { Person person = new Person(); Method method = person.getClass() @@ -33,24 +33,38 @@ public class AccessPrivateMethodsUnitTest { } @Test - public void whenMethodNotSetAccessible_thenIllegalAccessException() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + public void whenMethodNotSetAccessible_thenIllegalAccessException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { Person person = new Person(); Method method = person.getClass() .getDeclaredMethod("greet", String.class); - Assertions.assertThrows(IllegalAccessException.class, () -> method.invoke(person, "John")); + Assertions.assertThrows(IllegalAccessException.class, () -> method.invoke(person, "Jane")); } @Test - public void whenCallingMethodThrowsException_thenInvocationTargetException() throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + public void whenCallingMethodThrowsException_thenInvocationTargetException() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NullPointerException { Person person = new Person(); - Method method = person.getClass() .getDeclaredMethod("divideByZeroExample"); method.setAccessible(true); - Assertions.assertThrows(InvocationTargetException.class, () -> method.invoke(person)); } + @Test + public void whenAccessingWrongProperty_thenNoSuchMethodException() throws NoSuchMethodException, NullPointerException { + Person person = new Person(); + + Assertions.assertThrows(NoSuchMethodException.class, () -> person.getClass() + .getDeclaredMethod("greeting", String.class)); + } + + @Test + public void whenAccessingNullMethod_thenNullPointerException() throws NoSuchMethodException, NullPointerException { + Person person = new Person(); + + Assertions.assertThrows(NullPointerException.class, () -> person.getClass() + .getDeclaredMethod(null, String.class)); + } + } From 333dad149fcaec6fe36f64d0375d4b00f9029828 Mon Sep 17 00:00:00 2001 From: marcodenisi Date: Thu, 18 Jun 2020 17:49:10 +0200 Subject: [PATCH 005/155] BAEL-4083 - sample spring boot app with xml config and properties --- spring-boot-modules/pom.xml | 1 + spring-boot-modules/spring-boot-xml/pom.xml | 32 +++++++++++++++++++ .../java/com/baeldung/springbootxml/Pojo.java | 17 ++++++++++ .../SpringBootXmlApplication.java | 25 +++++++++++++++ .../SpringBootXmlWithConfigApplication.java | 23 +++++++++++++ .../src/main/resources/application.properties | 1 + .../src/main/resources/beans.xml | 13 ++++++++ .../src/main/resources/beansconf.xml | 15 +++++++++ 8 files changed, 127 insertions(+) create mode 100644 spring-boot-modules/spring-boot-xml/pom.xml create mode 100644 spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/Pojo.java create mode 100644 spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java create mode 100644 spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java create mode 100644 spring-boot-modules/spring-boot-xml/src/main/resources/application.properties create mode 100644 spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml create mode 100644 spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 7992c0ce12..8ef3d34056 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -57,6 +57,7 @@ spring-boot-springdoc spring-boot-testing spring-boot-vue + spring-boot-xml diff --git a/spring-boot-modules/spring-boot-xml/pom.xml b/spring-boot-modules/spring-boot-xml/pom.xml new file mode 100644 index 0000000000..dd575ff414 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/pom.xml @@ -0,0 +1,32 @@ + + + + parent-boot-2 + com.baeldung + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + 4.0.0 + + spring-boot-xml + + + + org.springframework.boot + spring-boot-starter + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/Pojo.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/Pojo.java new file mode 100644 index 0000000000..8c8b47ed40 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/Pojo.java @@ -0,0 +1,17 @@ +package com.baeldung.springbootxml; + +public class Pojo { + + private String field; + + public Pojo() { + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } +} diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java new file mode 100644 index 0000000000..1a0350fd26 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java @@ -0,0 +1,25 @@ +package com.baeldung.springbootxml; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@EnableAutoConfiguration +@ImportResource("classpath:beans.xml") +public class SpringBootXmlApplication implements CommandLineRunner { + + @Autowired private Pojo pojo; + + public static void main(String[] args) { + SpringApplication.run(SpringBootXmlApplication.class, args); + } + + public void run(String... args) { + System.out.println(pojo.getField()); + } + +} diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java new file mode 100644 index 0000000000..7c36ac7905 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java @@ -0,0 +1,23 @@ +package com.baeldung.springbootxml; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource("classpath:beansconf.xml") +public class SpringBootXmlWithConfigApplication implements CommandLineRunner { + + @Autowired private Pojo pojo; + + public static void main(String[] args) { + SpringApplication.run(SpringBootXmlWithConfigApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + System.out.println(pojo.getField()); + } +} diff --git a/spring-boot-modules/spring-boot-xml/src/main/resources/application.properties b/spring-boot-modules/spring-boot-xml/src/main/resources/application.properties new file mode 100644 index 0000000000..ab9de92c82 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/resources/application.properties @@ -0,0 +1 @@ +sample=string loaded from properties! \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml b/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml new file mode 100644 index 0000000000..9dac0d9e65 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml @@ -0,0 +1,13 @@ + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml b/spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml new file mode 100644 index 0000000000..7f328370a8 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml @@ -0,0 +1,15 @@ + + + + + + + + + \ No newline at end of file From 3cb402ced71073a70875cc770e2abc47b0e9ef5e Mon Sep 17 00:00:00 2001 From: marcodenisi Date: Thu, 18 Jun 2020 17:58:25 +0200 Subject: [PATCH 006/155] BAEL-4083 - removed sample with xml context-config --- .../SpringBootXmlApplication.java | 6 ++--- .../SpringBootXmlWithConfigApplication.java | 23 ------------------- .../src/main/resources/beansconf.xml | 15 ------------ 3 files changed, 2 insertions(+), 42 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java delete mode 100644 spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java index 1a0350fd26..bd75a95d7d 100644 --- a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java +++ b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java @@ -3,12 +3,10 @@ package com.baeldung.springbootxml; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Configuration; +import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; -@Configuration -@EnableAutoConfiguration +@SpringBootApplication @ImportResource("classpath:beans.xml") public class SpringBootXmlApplication implements CommandLineRunner { diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java deleted file mode 100644 index 7c36ac7905..0000000000 --- a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlWithConfigApplication.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.springbootxml; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.ImportResource; - -@Configuration -@ImportResource("classpath:beansconf.xml") -public class SpringBootXmlWithConfigApplication implements CommandLineRunner { - - @Autowired private Pojo pojo; - - public static void main(String[] args) { - SpringApplication.run(SpringBootXmlWithConfigApplication.class, args); - } - - @Override - public void run(String... args) throws Exception { - System.out.println(pojo.getField()); - } -} diff --git a/spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml b/spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml deleted file mode 100644 index 7f328370a8..0000000000 --- a/spring-boot-modules/spring-boot-xml/src/main/resources/beansconf.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - \ No newline at end of file From eaf59355892d58c92d04354d4a77c28d91b45a9f Mon Sep 17 00:00:00 2001 From: marcodenisi Date: Thu, 18 Jun 2020 22:41:36 +0200 Subject: [PATCH 007/155] add slfj logger --- .../springbootxml/SpringBootXmlApplication.java | 12 +++++++++--- .../spring-boot-xml/src/main/resources/beans.xml | 12 +++++------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java index bd75a95d7d..addf24c427 100644 --- a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java +++ b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplication.java @@ -1,15 +1,21 @@ package com.baeldung.springbootxml; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -@SpringBootApplication +@Configuration +@EnableAutoConfiguration @ImportResource("classpath:beans.xml") public class SpringBootXmlApplication implements CommandLineRunner { + private static final Logger logger = LoggerFactory.getLogger(SpringBootXmlApplication.class); + @Autowired private Pojo pojo; public static void main(String[] args) { @@ -17,7 +23,7 @@ public class SpringBootXmlApplication implements CommandLineRunner { } public void run(String... args) { - System.out.println(pojo.getField()); + logger.info(pojo.getField()); } } diff --git a/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml b/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml index 9dac0d9e65..200afecbc9 100644 --- a/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml +++ b/spring-boot-modules/spring-boot-xml/src/main/resources/beans.xml @@ -1,11 +1,9 @@ - + From efa72998e56e9bcbae6ab9b442dfa9cc463c58b0 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Fri, 19 Jun 2020 22:20:57 +0530 Subject: [PATCH 008/155] Added new test case for IllegalArgumentException --- .../privatefields/AccessPrivateFieldsUnitTest.java | 4 ++-- .../privatefields/AccessPrivateMethodsUnitTest.java | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index b885e3b669..c74af1fe90 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -28,13 +28,13 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void givenInt_whenSetStringField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void givenInt_whenGetStringField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); Field fieldName = person.getClass() .getDeclaredField("name"); fieldName.setAccessible(true); - Assertions.assertThrows(IllegalArgumentException.class, () -> fieldName.setInt(person, 25)); + Assertions.assertThrows(IllegalArgumentException.class, () -> fieldName.getInt(person)); } @Test diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java index 10c953f4af..df745897d2 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java @@ -31,6 +31,17 @@ public class AccessPrivateMethodsUnitTest { Assertions.assertThrows(IllegalArgumentException.class, () -> method.invoke(person, 25)); } + + @Test + public void givenMultipleParameters_whenInvokeMethod_thenIllegalArgumentException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { + Person person = new Person(); + + Method method = person.getClass() + .getDeclaredMethod("greet", String.class); + method.setAccessible(true); + + Assertions.assertThrows(IllegalArgumentException.class, () -> method.invoke(person, "John", "Jane")); + } @Test public void whenMethodNotSetAccessible_thenIllegalAccessException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { From 57dcc48b92144a6810453d754fa0f19f81090566 Mon Sep 17 00:00:00 2001 From: mdhtr Date: Mon, 22 Jun 2020 16:26:42 +0200 Subject: [PATCH 009/155] Examples for the first version of the article --- json-2/pom.xml | 60 +++++++++++++++++++ .../JacksonDeserializationExample.java | 40 +++++++++++++ .../jackson/JacksonExamplePerson.java | 19 ++++++ .../hydrajsonld/HydraJsonldExamplePerson.java | 15 +++++ .../HydraJsonldSerializationExample.java | 52 ++++++++++++++++ .../JacksonJsonLdSerializationExample.java | 25 ++++++++ .../JacksonJsonldExamplePerson.java | 17 ++++++ 7 files changed, 228 insertions(+) create mode 100644 json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java create mode 100644 json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java create mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java create mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java create mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java create mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java diff --git a/json-2/pom.xml b/json-2/pom.xml index e0295af59b..73c26e8259 100644 --- a/json-2/pom.xml +++ b/json-2/pom.xml @@ -49,6 +49,66 @@ commons-lang3 3.9 + + + com.fasterxml.jackson.core + jackson-annotations + 2.11.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.11.0 + + + com.io-informatics.oss + jackson-jsonld + 0.1.1 + + + jackson-databind + com.fasterxml.jackson.core + + + jackson-annotations + com.fasterxml.jackson.core + + + jackson-core + com.fasterxml.jackson.core + + + jsonld-java + com.github.jsonld-java + + + + + de.escalon.hypermedia + hydra-jsonld + 0.4.2 + + + jackson-databind + com.fasterxml.jackson.core + + + + + com.github.jsonld-java + jsonld-java + 0.13.0 + + + jackson-core + com.fasterxml.jackson.core + + + jackson-databind + com.fasterxml.jackson.core + + + 0.9.23 diff --git a/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java b/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java new file mode 100644 index 0000000000..b80769b408 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java @@ -0,0 +1,40 @@ +package com.baeldung.jsonld.deserialization.jsonldjava.jackson; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.jsonldjava.core.JsonLdOptions; +import com.github.jsonldjava.core.JsonLdProcessor; +import com.github.jsonldjava.utils.JsonUtils; + +public class JacksonDeserializationExample { + public static void main(String[] args) throws IOException { + String exampleJsonld ="{" + + " \"@context\": {" + + " \"@vocab\": \"http://schema.org/\"," + + " \"knows\": {" + + " \"@type\": \"@id\"" + + " }" + + " }," + + " \"@type\": \"Person\"," + + " \"@id\": \"http://example.com/person/1234\"," + + " \"name\": \"Example Name\"," + + " \"knows\": \"http://example.com/person/2345\"" + + "}"; + + Object jsonObject = JsonUtils.fromString(exampleJsonld); + Object compact = JsonLdProcessor.compact(jsonObject, new HashMap(), new JsonLdOptions()); + String compactContent = JsonUtils.toString(compact); + + System.out.println(JsonUtils.toPrettyString(compact)); + + ObjectMapper objectMapper = new ObjectMapper(); + JacksonExamplePerson person = objectMapper.readValue(compactContent, JacksonExamplePerson.class); + + System.out.println(person.id); + System.out.println(person.name); + System.out.println(person.knows.id); + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java b/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java new file mode 100644 index 0000000000..2e9f38e665 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java @@ -0,0 +1,19 @@ +package com.baeldung.jsonld.deserialization.jsonldjava.jackson; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class JacksonExamplePerson { + @JsonProperty("@id") + public String id; + @JsonProperty("http://schema.org/name") + public String name; + @JsonProperty("http://schema.org/knows") + public Link knows; + + public class Link { + @JsonProperty("@id") + public String id; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java new file mode 100644 index 0000000000..16b2199a73 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java @@ -0,0 +1,15 @@ +package com.baeldung.jsonld.serialization.hydrajsonld; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import de.escalon.hypermedia.hydra.mapping.Expose; +import de.escalon.hypermedia.hydra.mapping.Vocab; + +@Vocab("http://example.com/vocab/") +@Expose("person") +public class HydraJsonldExamplePerson { + @JsonProperty("@id") + public String id; + @Expose("fullName") + public String name; +} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java new file mode 100644 index 0000000000..3d3531b0b5 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java @@ -0,0 +1,52 @@ +package com.baeldung.jsonld.serialization.hydrajsonld; + +import java.io.IOException; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.BeanDescription; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationConfig; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; +import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; + +import de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer; + +public class HydraJsonldSerializationExample { + public static void main(String[] args) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.registerModule(getJacksonHydraSerializerModule()); + + HydraJsonldExamplePerson person = new HydraJsonldExamplePerson(); + person.id = "http://example.com/person/1234"; + person.name = "Example Name"; + + System.out.println(mapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(person)); + } + + public static SimpleModule getJacksonHydraSerializerModule() { + return new SimpleModule() { + + @Override + public void setupModule(SetupContext context) { + super.setupModule(context); + + context.addBeanSerializerModifier(new BeanSerializerModifier() { + + @Override + public JsonSerializer modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer serializer) { + + if (serializer instanceof BeanSerializerBase) { + return new JacksonHydraSerializer((BeanSerializerBase) serializer); + } else { + return serializer; + } + } + }); + } + }; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java new file mode 100644 index 0000000000..6a1acee1b8 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java @@ -0,0 +1,25 @@ +package com.baeldung.jsonld.serialization.jacksonjsonld; + +import java.io.IOException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import ioinformarics.oss.jackson.module.jsonld.HydraCollection; +import ioinformarics.oss.jackson.module.jsonld.JsonldGraph; +import ioinformarics.oss.jackson.module.jsonld.JsonldModule; +import ioinformarics.oss.jackson.module.jsonld.JsonldResource; + +public class JacksonJsonLdSerializationExample { + public static void main(String[] args) throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JsonldModule()); + + JacksonJsonldExamplePerson person = new JacksonJsonldExamplePerson(); + + JsonldResource jsonldResource = JsonldResource.Builder.create() + .build(person); + + System.out.println(objectMapper.writerWithDefaultPrettyPrinter() + .writeValueAsString(jsonldResource)); + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java new file mode 100644 index 0000000000..a3161ba1d3 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java @@ -0,0 +1,17 @@ +package com.baeldung.jsonld.serialization.jacksonjsonld; + +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldId; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldLink; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldNamespace; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldProperty; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType; + +@JsonldNamespace(name = "s", uri = "http://schema.org/") +@JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345") +@JsonldType("s:Person") +class JacksonJsonldExamplePerson { + @JsonldId + public String id = "http://example.com/person/1234"; + @JsonldProperty("s:name") + public String name = "Example Name"; +} From a951d80b419ef562f688a1afaae492098eb3e66e Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 23 Jun 2020 21:48:01 +0530 Subject: [PATCH 010/155] Removed test cases for getting private methods --- .../AccessPrivateMethodsUnitTest.java | 81 ------------------- 1 file changed, 81 deletions(-) delete mode 100644 core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java deleted file mode 100644 index df745897d2..0000000000 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateMethodsUnitTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.reflection.access.privatefields; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class AccessPrivateMethodsUnitTest { - - @Test - public void whenGetMethod_thenSuccess() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NullPointerException { - Person person = new Person(); - - Method method = person.getClass() - .getDeclaredMethod("greet", String.class); - method.setAccessible(true); - - String greetMessage = (String) method.invoke(person, "Jane"); - - Assertions.assertEquals("Hello Jane", greetMessage); - } - - @Test - public void givenInt_whenInvokeMethod_thenIllegalArgumentException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { - Person person = new Person(); - - Method method = person.getClass() - .getDeclaredMethod("greet", String.class); - method.setAccessible(true); - - Assertions.assertThrows(IllegalArgumentException.class, () -> method.invoke(person, 25)); - } - - @Test - public void givenMultipleParameters_whenInvokeMethod_thenIllegalArgumentException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { - Person person = new Person(); - - Method method = person.getClass() - .getDeclaredMethod("greet", String.class); - method.setAccessible(true); - - Assertions.assertThrows(IllegalArgumentException.class, () -> method.invoke(person, "John", "Jane")); - } - - @Test - public void whenMethodNotSetAccessible_thenIllegalAccessException() throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, NullPointerException { - Person person = new Person(); - - Method method = person.getClass() - .getDeclaredMethod("greet", String.class); - - Assertions.assertThrows(IllegalAccessException.class, () -> method.invoke(person, "Jane")); - } - - @Test - public void whenCallingMethodThrowsException_thenInvocationTargetException() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NullPointerException { - Person person = new Person(); - Method method = person.getClass() - .getDeclaredMethod("divideByZeroExample"); - method.setAccessible(true); - Assertions.assertThrows(InvocationTargetException.class, () -> method.invoke(person)); - } - - @Test - public void whenAccessingWrongProperty_thenNoSuchMethodException() throws NoSuchMethodException, NullPointerException { - Person person = new Person(); - - Assertions.assertThrows(NoSuchMethodException.class, () -> person.getClass() - .getDeclaredMethod("greeting", String.class)); - } - - @Test - public void whenAccessingNullMethod_thenNullPointerException() throws NoSuchMethodException, NullPointerException { - Person person = new Person(); - - Assertions.assertThrows(NullPointerException.class, () -> person.getClass() - .getDeclaredMethod(null, String.class)); - } - -} From 885278e502f896f232b712038613bb7c8b01ec62 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Tue, 23 Jun 2020 21:49:35 +0530 Subject: [PATCH 011/155] Added test cases for accessing all data types. --- .../access/privatefields/Person.java | 76 +++++++++++++-- .../AccessPrivateFieldsUnitTest.java | 95 ++++++++++++++++--- 2 files changed, 153 insertions(+), 18 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java index 2ec263f6ae..433dc7636d 100755 --- a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java @@ -4,7 +4,21 @@ public class Person { private String name = "John"; - private int age = 30; + private byte age = 30; + + private short uidNumber = 5555; + + private int pinCode = 452002; + + private long contactNumber = 123456789L; + + private float height = 6.1242f; + + private double weight = 75.2564; + + private char gender = 'M'; + + private boolean active = true; public String getName() { return name; @@ -14,20 +28,68 @@ public class Person { this.name = name; } - public int getAge() { + public byte getAge() { return age; } - public void setAge(int age) { + public void setAge(byte age) { this.age = age; } - private String greet(String name) { - return "Hello " + name; + public short getUidNumber() { + return uidNumber; } - private int divideByZeroExample() { - return 1 / 0; + public void setUidNumber(short uidNumber) { + this.uidNumber = uidNumber; + } + + public int getPinCode() { + return pinCode; + } + + public void setPinCode(int pinCode) { + this.pinCode = pinCode; + } + + public long getContactNumber() { + return contactNumber; + } + + public void setContactNumber(long contactNumber) { + this.contactNumber = contactNumber; + } + + public float getHeight() { + return height; + } + + public void setHeight(float height) { + this.height = height; + } + + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + this.weight = weight; + } + + public char getGender() { + return gender; + } + + public void setGender(char gender) { + this.gender = gender; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; } } diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index c74af1fe90..69f3eebe71 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -11,39 +11,112 @@ public class AccessPrivateFieldsUnitTest { public void whenGetFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - Field fieldName = person.getClass() + Field nameField = person.getClass() .getDeclaredField("name"); - fieldName.setAccessible(true); + nameField.setAccessible(true); - String name = (String) fieldName.get(person); + String name = (String) nameField.get(person); - Field fieldAge = person.getClass() + Field ageField = person.getClass() .getDeclaredField("age"); - fieldAge.setAccessible(true); + ageField.setAccessible(true); - int age = fieldAge.getInt(person); + byte age = ageField.getByte(person); Assertions.assertEquals("John", name); Assertions.assertEquals(30, age); } + @Test + public void whenGetIntegerFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field uidNumberField = person.getClass() + .getDeclaredField("uidNumber"); + uidNumberField.setAccessible(true); + + short uidNumber = uidNumberField.getShort(person); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + int pinCode = pinCodeField.getInt(person); + + Field contactNumberField = person.getClass() + .getDeclaredField("contactNumber"); + contactNumberField.setAccessible(true); + + long contactNumber = contactNumberField.getLong(person); + + Assertions.assertEquals(5555, uidNumber); + Assertions.assertEquals(452002, pinCode); + Assertions.assertEquals(123456789L, contactNumber); + } + + @Test + public void whenGetFloatingTypeFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field heightField = person.getClass() + .getDeclaredField("height"); + heightField.setAccessible(true); + + float height = heightField.getFloat(person); + + Field weightField = person.getClass() + .getDeclaredField("weight"); + weightField.setAccessible(true); + + double weight = weightField.getDouble(person); + + Assertions.assertEquals(6.1242f, height); + Assertions.assertEquals(75.2564, weight); + } + + @Test + public void whenGetCharacterFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field genderField = person.getClass() + .getDeclaredField("gender"); + genderField.setAccessible(true); + + char gender = genderField.getChar(person); + + Assertions.assertEquals('M', gender); + } + + @Test + public void whenGetBooleanFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field activeField = person.getClass() + .getDeclaredField("active"); + activeField.setAccessible(true); + + boolean active = activeField.getBoolean(person); + + Assertions.assertTrue(active); + } + @Test public void givenInt_whenGetStringField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - Field fieldName = person.getClass() + Field nameField = person.getClass() .getDeclaredField("name"); - fieldName.setAccessible(true); + nameField.setAccessible(true); - Assertions.assertThrows(IllegalArgumentException.class, () -> fieldName.getInt(person)); + Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.getInt(person)); } @Test public void whenFieldNotSetAccessible_thenIllegalAccessException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - Field fieldName = person.getClass() + Field nameField = person.getClass() .getDeclaredField("name"); - Assertions.assertThrows(IllegalAccessException.class, () -> fieldName.get(person)); + Assertions.assertThrows(IllegalAccessException.class, () -> nameField.get(person)); } @Test From 0e528b11d2fd5d832b2d040bdf5c65214c60bdaf Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sat, 27 Jun 2020 16:33:20 +0530 Subject: [PATCH 012/155] Segregated test cases for primitive and object types. Added test case for Autoboxing. --- .../AccessPrivateFieldsUnitTest.java | 50 +++++++++++-------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index 69f3eebe71..bf9e4ea591 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -8,50 +8,49 @@ import org.junit.jupiter.api.Test; public class AccessPrivateFieldsUnitTest { @Test - public void whenGetFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenGetIntegerFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); - Field nameField = person.getClass() - .getDeclaredField("name"); - nameField.setAccessible(true); - - String name = (String) nameField.get(person); - Field ageField = person.getClass() .getDeclaredField("age"); ageField.setAccessible(true); byte age = ageField.getByte(person); - - Assertions.assertEquals("John", name); Assertions.assertEquals(30, age); - } - - @Test - public void whenGetIntegerFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { - Person person = new Person(); Field uidNumberField = person.getClass() .getDeclaredField("uidNumber"); uidNumberField.setAccessible(true); short uidNumber = uidNumberField.getShort(person); + Assertions.assertEquals(5555, uidNumber); Field pinCodeField = person.getClass() .getDeclaredField("pinCode"); pinCodeField.setAccessible(true); int pinCode = pinCodeField.getInt(person); + Assertions.assertEquals(452002, pinCode); Field contactNumberField = person.getClass() .getDeclaredField("contactNumber"); contactNumberField.setAccessible(true); long contactNumber = contactNumberField.getLong(person); - - Assertions.assertEquals(5555, uidNumber); - Assertions.assertEquals(452002, pinCode); Assertions.assertEquals(123456789L, contactNumber); + + } + + @Test + public void whenDoAutoboxing_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + Integer pinCode = pinCodeField.getInt(person); + Assertions.assertEquals(452002, pinCode); } @Test @@ -63,14 +62,13 @@ public class AccessPrivateFieldsUnitTest { heightField.setAccessible(true); float height = heightField.getFloat(person); + Assertions.assertEquals(6.1242f, height); Field weightField = person.getClass() .getDeclaredField("weight"); weightField.setAccessible(true); double weight = weightField.getDouble(person); - - Assertions.assertEquals(6.1242f, height); Assertions.assertEquals(75.2564, weight); } @@ -83,7 +81,6 @@ public class AccessPrivateFieldsUnitTest { genderField.setAccessible(true); char gender = genderField.getChar(person); - Assertions.assertEquals('M', gender); } @@ -96,10 +93,21 @@ public class AccessPrivateFieldsUnitTest { activeField.setAccessible(true); boolean active = activeField.getBoolean(person); - Assertions.assertTrue(active); } + @Test + public void whenGetObjectFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field nameField = person.getClass() + .getDeclaredField("name"); + nameField.setAccessible(true); + + String name = (String) nameField.get(person); + Assertions.assertEquals("John", name); + } + @Test public void givenInt_whenGetStringField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); From 5236d6ceddda702cde8c06e9ffef7975e871756a Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sat, 27 Jun 2020 16:39:16 +0530 Subject: [PATCH 013/155] Condensed fields by removing extra space. --- .../baeldung/reflection/access/privatefields/Person.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java index 433dc7636d..4e2f0fc0cc 100755 --- a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java +++ b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java @@ -3,21 +3,13 @@ package com.baeldung.reflection.access.privatefields; public class Person { private String name = "John"; - private byte age = 30; - private short uidNumber = 5555; - private int pinCode = 452002; - private long contactNumber = 123456789L; - private float height = 6.1242f; - private double weight = 75.2564; - private char gender = 'M'; - private boolean active = true; public String getName() { From c5f8489f1d347ea83939cba014dc3f857810a5b1 Mon Sep 17 00:00:00 2001 From: Marco Denisi Date: Sun, 28 Jun 2020 10:15:48 +0200 Subject: [PATCH 014/155] BAEL-4083 - add app integration test --- spring-boot-modules/spring-boot-xml/pom.xml | 8 ++++++ ...ringBootXmlApplicationIntegrationTest.java | 26 +++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplicationIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-xml/pom.xml b/spring-boot-modules/spring-boot-xml/pom.xml index dd575ff414..e1ddd8f437 100644 --- a/spring-boot-modules/spring-boot-xml/pom.xml +++ b/spring-boot-modules/spring-boot-xml/pom.xml @@ -18,6 +18,14 @@ org.springframework.boot spring-boot-starter + + org.springframework.boot + spring-boot-starter-test + + + junit + junit + diff --git a/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplicationIntegrationTest.java new file mode 100644 index 0000000000..2c3993d0d8 --- /dev/null +++ b/spring-boot-modules/spring-boot-xml/src/main/java/com/baeldung/springbootxml/SpringBootXmlApplicationIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.springbootxml; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootXmlApplication.class) +public class SpringBootXmlApplicationIntegrationTest { + + @Autowired private Pojo pojo; + @Value("${sample}") private String sample; + + @Test + public void whenCallingGetter_thenPrintingProperty() { + assertThat(pojo.getField()) + .isNotBlank() + .isEqualTo(sample); + } + +} \ No newline at end of file From 67e9dc8187222f9746889f090cef492425ab1fce Mon Sep 17 00:00:00 2001 From: STS Date: Sun, 28 Jun 2020 20:33:10 +0200 Subject: [PATCH 015/155] add excel formula --- excelformula/.gitignore | 34 +++++++++++ excelformula/pom.xml | 57 +++++++++++++++++++ .../poi/excelformula/ExcelFormula.java | 36 ++++++++++++ .../excelformula/ExcelformulaApplication.java | 13 +++++ .../src/main/resources/application.properties | 1 + .../ExcelformulaApplicationTests.java | 38 +++++++++++++ 6 files changed, 179 insertions(+) create mode 100644 excelformula/.gitignore create mode 100644 excelformula/pom.xml create mode 100644 excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java create mode 100644 excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java create mode 100644 excelformula/src/main/resources/application.properties create mode 100644 excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java diff --git a/excelformula/.gitignore b/excelformula/.gitignore new file mode 100644 index 0000000000..719e322c1d --- /dev/null +++ b/excelformula/.gitignore @@ -0,0 +1,34 @@ +HELP.md +mvnw +mvnw.cmd +.mvn +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/excelformula/pom.xml b/excelformula/pom.xml new file mode 100644 index 0000000000..4ea65b5e57 --- /dev/null +++ b/excelformula/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + com.bealdung.poi + excelformula + 0.0.1-SNAPSHOT + excelformula + Demo project for Spring Boot + + 11 + 4.1.2 + 4.13 + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.apache.poi + poi-ooxml + ${poi-ooxml.version} + + + junit + junit + ${junit.version} + test + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java b/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java new file mode 100644 index 0000000000..1e2fa5acfe --- /dev/null +++ b/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java @@ -0,0 +1,36 @@ +package com.bealdung.poi.excelformula; + +import org.apache.poi.ss.usermodel.CellValue; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.List; + +@Component +public class ExcelFormula { + XSSFWorkbook excel; + public XSSFSheet inserData(List dataList) { + excel = new XSSFWorkbook(); + XSSFSheet sheet = excel.createSheet(); + int rowNum =0 ; + for (Integer data : dataList){ + sheet.createRow(rowNum++).createCell(0).setCellValue(data); + } + return sheet; + } + public double setFormula(String formula) throws IOException { + XSSFSheet sheet = excel.getSheetAt(0); + int lastCellNum = sheet.getRow(0).getLastCellNum(); + XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum + 1); + formulaCell.setCellFormula(formula); + XSSFFormulaEvaluator formulaEvaluator = excel.getCreationHelper().createFormulaEvaluator(); + CellValue evaluate = formulaEvaluator.evaluate(formulaCell); + if(excel != null) + excel.close(); + return evaluate.getNumberValue(); + } +} diff --git a/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java b/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java new file mode 100644 index 0000000000..b857bd4266 --- /dev/null +++ b/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java @@ -0,0 +1,13 @@ +package com.bealdung.poi.excelformula; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ExcelformulaApplication { + + public static void main(String[] args) { + SpringApplication.run(ExcelformulaApplication.class, args); + } + +} diff --git a/excelformula/src/main/resources/application.properties b/excelformula/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/excelformula/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java b/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java new file mode 100644 index 0000000000..c2385911d0 --- /dev/null +++ b/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java @@ -0,0 +1,38 @@ +package com.bealdung.poi.excelformula; + +import org.apache.poi.ss.util.CellReference; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.junit.Assert; +import org.junit.jupiter.api.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.io.IOException; +import java.util.Arrays; +import java.util.List; + +@RunWith(SpringRunner.class) +@SpringBootTest +class ExcelformulaApplicationTests { + @Autowired + private ExcelFormula excelFormula; + + @Test + void givenExcelData_whenSetAndEvaluateFormula() throws IOException { + List data = Arrays.asList(2, 5, 10, 15, 7, 9); + XSSFSheet sheet = excelFormula.inserData(data); + int result = 0; + for (int row = 0; row <= sheet.getLastRowNum(); row++) { + result += sheet.getRow(row).getCell(0).getNumericCellValue(); + } + String colName = CellReference.convertNumToColString(0); + String startCell = colName + 1; + String stopCell = colName + (sheet.getLastRowNum() + 1); + String sumFormula = String.format("SUM(%s:%s)", startCell, stopCell); + int resultValue = (int) excelFormula.setFormula(sumFormula); + Assert.assertEquals("The results are the same!", resultValue , result); + } + +} From ecde6b58a83eb964a66e3cf5e9ebef7428018e05 Mon Sep 17 00:00:00 2001 From: STS Date: Sun, 28 Jun 2020 21:12:09 +0200 Subject: [PATCH 016/155] create README.md file --- excelformula/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 excelformula/README.md diff --git a/excelformula/README.md b/excelformula/README.md new file mode 100644 index 0000000000..86ddaba413 --- /dev/null +++ b/excelformula/README.md @@ -0,0 +1,8 @@ +## Apache POI + +This module contains articles about Apache POI + +### Relevant Articles: +- [Working with Microsoft Excel in Java](https://www.baeldung.com/java-microsoft-excel) +- [Read Excel Cell Value Rather Than Formula With Apache POI](https://www.baeldung.com/apache-poi-read-cell-value-formula) +- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) From 12eb8523493e790d2cb232f902035e290fc0a097 Mon Sep 17 00:00:00 2001 From: STS Date: Mon, 29 Jun 2020 14:07:18 +0200 Subject: [PATCH 017/155] remove and add file --- {excelformula => apache-poi/excelformula}/.gitignore | 0 {excelformula => apache-poi/excelformula}/pom.xml | 0 .../src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java | 0 .../com/bealdung/poi/excelformula/ExcelformulaApplication.java | 0 .../excelformula}/src/main/resources/application.properties | 0 .../bealdung/poi/excelformula/ExcelformulaApplicationTests.java | 0 6 files changed, 0 insertions(+), 0 deletions(-) rename {excelformula => apache-poi/excelformula}/.gitignore (100%) rename {excelformula => apache-poi/excelformula}/pom.xml (100%) rename {excelformula => apache-poi/excelformula}/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java (100%) rename {excelformula => apache-poi/excelformula}/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java (100%) rename {excelformula => apache-poi/excelformula}/src/main/resources/application.properties (100%) rename {excelformula => apache-poi/excelformula}/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java (100%) diff --git a/excelformula/.gitignore b/apache-poi/excelformula/.gitignore similarity index 100% rename from excelformula/.gitignore rename to apache-poi/excelformula/.gitignore diff --git a/excelformula/pom.xml b/apache-poi/excelformula/pom.xml similarity index 100% rename from excelformula/pom.xml rename to apache-poi/excelformula/pom.xml diff --git a/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java b/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java similarity index 100% rename from excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java rename to apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java diff --git a/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java b/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java similarity index 100% rename from excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java rename to apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java diff --git a/excelformula/src/main/resources/application.properties b/apache-poi/excelformula/src/main/resources/application.properties similarity index 100% rename from excelformula/src/main/resources/application.properties rename to apache-poi/excelformula/src/main/resources/application.properties diff --git a/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java b/apache-poi/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java similarity index 100% rename from excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java rename to apache-poi/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java From 0549f755b08b7f1c5b529d4cec42483d46a072f2 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Mon, 29 Jun 2020 22:27:35 +0530 Subject: [PATCH 018/155] Added test case for widening. --- .../AccessPrivateFieldsUnitTest.java | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index bf9e4ea591..5a2a33fa8f 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -53,6 +53,18 @@ public class AccessPrivateFieldsUnitTest { Assertions.assertEquals(452002, pinCode); } + @Test + public void whenDoWidening_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + Long pinCode = pinCodeField.getLong(person); + Assertions.assertEquals(452002L, pinCode); + } + @Test public void whenGetFloatingTypeFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); @@ -118,6 +130,16 @@ public class AccessPrivateFieldsUnitTest { Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.getInt(person)); } + @Test + public void givenInt_whenGetLongField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + Person person = new Person(); + Field contactNumberField = person.getClass() + .getDeclaredField("contactNumber"); + contactNumberField.setAccessible(true); + + Assertions.assertThrows(IllegalArgumentException.class, () -> contactNumberField.getInt(person)); + } + @Test public void whenFieldNotSetAccessible_thenIllegalAccessException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { Person person = new Person(); @@ -132,7 +154,7 @@ public class AccessPrivateFieldsUnitTest { Person person = new Person(); Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass() - .getDeclaredField("genders")); + .getDeclaredField("firstName")); } @Test From d1a9ff7480f8f21543c02d61992d0dd20fa4e56d Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 30 Jun 2020 15:52:17 +0200 Subject: [PATCH 019/155] [BAEL-4281] Examples of array comparisons --- java-collections/README.md | 8 +++ java-collections/pom.xml | 49 +++++++++++++++++++ .../com/baeldung/comparingarrays/Plane.java | 39 +++++++++++++++ .../src/main/resources/logback.xml | 13 +++++ .../baeldung/DeepEqualsCompareUnitTest.java | 34 +++++++++++++ .../com/baeldung/EqualsCompareUnitTest.java | 29 +++++++++++ .../com/baeldung/LengthsCompareUnitTest.java | 22 +++++++++ .../com/baeldung/OrderCompareUnitTest.java | 34 +++++++++++++ .../baeldung/ReferenceCompareUnitTest.java | 34 +++++++++++++ 9 files changed, 262 insertions(+) create mode 100644 java-collections/README.md create mode 100644 java-collections/pom.xml create mode 100644 java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java create mode 100644 java-collections/src/main/resources/logback.xml create mode 100644 java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java create mode 100644 java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java create mode 100644 java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java create mode 100644 java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java create mode 100644 java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java diff --git a/java-collections/README.md b/java-collections/README.md new file mode 100644 index 0000000000..480b7f257a --- /dev/null +++ b/java-collections/README.md @@ -0,0 +1,8 @@ +## Java Collections Examples + +This module support code for articles about handling java collections and arrays. + +### Relevant Articles: +- [Comparing two integer arrays in Java](https://stackoverflow.com/questions/14897366/comparing-two-integer-arrays-in-java) +- [Compare two arrays with not the same order](https://stackoverflow.com/questions/54711228/compare-two-arrays-with-not-the-same-order) +- More articles: [[next -->]](../java-collections-conversions-2) \ No newline at end of file diff --git a/java-collections/pom.xml b/java-collections/pom.xml new file mode 100644 index 0000000000..5e0ee42244 --- /dev/null +++ b/java-collections/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + java-collections + 0.1.0-SNAPSHOT + java-collections + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.hamcrest + hamcrest-all + ${hamcrest-all.version} + test + + + + + java-collections + + + src/main/resources + true + + + + + + 4.1 + + diff --git a/java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java b/java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java new file mode 100644 index 0000000000..db61807878 --- /dev/null +++ b/java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java @@ -0,0 +1,39 @@ +package com.baeldung.comparingarrays; + +import java.util.Objects; + +public class Plane { + + private final String name; + + private final String model; + + public Plane(String name, String model) { + + this.name = name; + this.model = model; + } + + public String getName() { + return name; + } + + public String getModel() { + return model; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Plane plane = (Plane) o; + return Objects.equals(name, plane.name) && Objects.equals(model, plane.model); + } + + @Override + public int hashCode() { + return Objects.hash(name, model); + } +} diff --git a/java-collections/src/main/resources/logback.xml b/java-collections/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-collections/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java new file mode 100644 index 0000000000..f311d0e5c9 --- /dev/null +++ b/java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import com.baeldung.comparingarrays.Plane; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class DeepEqualsCompareUnitTest { + + @Test + public void givenArray1andArray2_whenSameContent_thenDeepEquals() { + final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, + new Plane[] { new Plane("Plane 2", "B738") } }; + final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, + new Plane[] { new Plane("Plane 2", "B738") } }; + + boolean result = Arrays.deepEquals(planes1, planes2); + assertTrue("Result is not true", result); + } + + @Test + public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { + final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, + new Plane[] { new Plane("Plane 2", "B738") } }; + final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") }, + new Plane[] { new Plane("Plane 1", "A320") } }; + + boolean result = Arrays.deepEquals(planes1, planes2); + assertFalse("Result is true", result); + } +} diff --git a/java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java new file mode 100644 index 0000000000..b56395a848 --- /dev/null +++ b/java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class EqualsCompareUnitTest { + + @Test + public void givenArray1andArray2_whenSameContent_thenEquals() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + + boolean result = Arrays.equals(planes1, planes2); + assertTrue("Result is not true", result); + } + + @Test + public void givenArray1andArray2_whenSameContentOtherSort_thenNotEquals() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" }; + + boolean result = Arrays.equals(planes1, planes2); + assertFalse("Result is true", result); + } +} diff --git a/java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java new file mode 100644 index 0000000000..8b3c90c427 --- /dev/null +++ b/java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; +import static org.junit.Assert.assertThat; + +public class LengthsCompareUnitTest { + + @Test + public void givenArray1andArray2_whenSameSizes_thenSizeEqualsOk() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 }; + + assertThat(planes1, arrayWithSize(8)); + assertThat(quantities, arrayWithSize(8)); + assertThat(planes1.length, is(8)); + assertThat(quantities.length, is(8)); + } +} + diff --git a/java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java new file mode 100644 index 0000000000..8be7251c05 --- /dev/null +++ b/java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import com.baeldung.comparingarrays.Plane; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Comparator; + +import static org.junit.Assert.assertTrue; + +public class OrderCompareUnitTest { + @Test + public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { + final Plane[][] planes1 = new Plane[][] { + new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } }; + final Plane[][] planes2 = new Plane[][] { + new Plane[] { new Plane("Plane 2", "B738"), new Plane("Plane 1", "A320") } }; + + Comparator planeComparator = (o1, o2) -> { + if (o1.getName() + .equals(o2.getName())) { + return o2.getModel() + .compareTo(o1.getModel()); + } + return o2.getName() + .compareTo(o1.getName()); + }; + Arrays.sort(planes1[0], planeComparator); + Arrays.sort(planes2[0], planeComparator); + + boolean result = Arrays.deepEquals(planes1, planes2); + assertTrue("Result is false", result); + } +} diff --git a/java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java new file mode 100644 index 0000000000..9716a34607 --- /dev/null +++ b/java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung; + +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +public class ReferenceCompareUnitTest { + + @Test + public void givenArray1andArray2_whenEquals_thenEqual() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = planes1; + + assertSame("Objects are not equal!", planes1, planes2); + + planes2[0] = "747"; + + assertSame("Objects are not same!", planes1, planes2); + assertEquals("Objects are not equal!", "747", planes2[0]); + assertEquals("Objects are not equal!", "747", planes1[0]); + } + + @Test + public void givenArray1andArray2_whenDifferentValues_thenNotEqual() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + + assertNotSame("Objects are the same!", planes1, planes2); + assertNotEquals("Objects are equal!", planes1, planes2); + } +} From 6182cdf09f56fc11a852a784371427a2b9705eea Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 3 Jul 2020 17:18:39 +0530 Subject: [PATCH 020/155] gupta.aashishrules@gmail.com - Hexagonal gupta.aashishrules@gmail.com - Hexagonal --- bookstore/pom.xml | 23 +++++++++++ .../src/main/java/com/hexagonal/MainApp.java | 13 +++++++ .../hexagonal/controller/BookController.java | 37 ++++++++++++++++++ .../main/java/com/hexagonal/domain/Book.java | 38 +++++++++++++++++++ .../hexagonal/repository/BookRepository.java | 15 ++++++++ .../repository/BookRepositoryImpl.java | 35 +++++++++++++++++ .../com/hexagonal/service/BookService.java | 15 ++++++++ .../hexagonal/service/BookServiceImpl.java | 35 +++++++++++++++++ 8 files changed, 211 insertions(+) create mode 100644 bookstore/pom.xml create mode 100644 bookstore/src/main/java/com/hexagonal/MainApp.java create mode 100644 bookstore/src/main/java/com/hexagonal/controller/BookController.java create mode 100644 bookstore/src/main/java/com/hexagonal/domain/Book.java create mode 100644 bookstore/src/main/java/com/hexagonal/repository/BookRepository.java create mode 100644 bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java create mode 100644 bookstore/src/main/java/com/hexagonal/service/BookService.java create mode 100644 bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java diff --git a/bookstore/pom.xml b/bookstore/pom.xml new file mode 100644 index 0000000000..68286076e5 --- /dev/null +++ b/bookstore/pom.xml @@ -0,0 +1,23 @@ + + 4.0.0 + com.hexagonal + bookstore + 0.0.1-SNAPSHOT + + + 1.8 + + + + org.springframework.boot + spring-boot-starter-parent + 2.3.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + \ No newline at end of file diff --git a/bookstore/src/main/java/com/hexagonal/MainApp.java b/bookstore/src/main/java/com/hexagonal/MainApp.java new file mode 100644 index 0000000000..0d6ef861b3 --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/MainApp.java @@ -0,0 +1,13 @@ +package com.hexagonal; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; + +@SpringBootApplication +public class MainApp { + public static void main(String[] args) { + SpringApplication.run(MainApp.class, args); + } + +} \ No newline at end of file diff --git a/bookstore/src/main/java/com/hexagonal/controller/BookController.java b/bookstore/src/main/java/com/hexagonal/controller/BookController.java new file mode 100644 index 0000000000..7e525deaa1 --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/controller/BookController.java @@ -0,0 +1,37 @@ +package com.hexagonal.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +import com.hexagonal.domain.Book; +import com.hexagonal.service.BookService; + +@RestController +public class BookController { + + @Autowired + private BookService bookService; + + @RequestMapping("/book/add") + @PostMapping(produces = { MediaType.TEXT_PLAIN_VALUE }) + public void addBook(@RequestBody Book book) { + bookService.addBook(book); + } + + public Book buyBook(@PathVariable String isbn) { + return bookService.buyBook(isbn); + } + + public List listBooks() { + return bookService.listBooks(); + } + +} diff --git a/bookstore/src/main/java/com/hexagonal/domain/Book.java b/bookstore/src/main/java/com/hexagonal/domain/Book.java new file mode 100644 index 0000000000..84125391cc --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/domain/Book.java @@ -0,0 +1,38 @@ +package com.hexagonal.domain; + +public class Book { + + private String name; + private String isbn; + private String author; + + @Override + public String toString() { + return "Book [name=" + name + ", ISBN=" + isbn + ", author=" + author + "]"; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + +} diff --git a/bookstore/src/main/java/com/hexagonal/repository/BookRepository.java b/bookstore/src/main/java/com/hexagonal/repository/BookRepository.java new file mode 100644 index 0000000000..1e64a2d21b --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/repository/BookRepository.java @@ -0,0 +1,15 @@ +package com.hexagonal.repository; + +import java.util.List; + +import com.hexagonal.domain.Book; + +public interface BookRepository { + + public void add(Book book); + + public Book buy(String isbn); + + public List list(); + +} diff --git a/bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java b/bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java new file mode 100644 index 0000000000..f4f99583dd --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java @@ -0,0 +1,35 @@ +package com.hexagonal.repository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.stereotype.Repository; + +import com.hexagonal.domain.Book; + +@Repository +public class BookRepositoryImpl implements BookRepository { + + private Map bookMap = new HashMap<>(); + + @Override + public void add(Book book) { + bookMap.put(book.getIsbn(), book); + System.out.println("Book Added " + book); + } + + @Override + public Book buy(String isbn) { + return bookMap.get(isbn); + } + + @Override + public List list() { + return bookMap.values() + .stream() + .collect(Collectors.toList()); + } + +} diff --git a/bookstore/src/main/java/com/hexagonal/service/BookService.java b/bookstore/src/main/java/com/hexagonal/service/BookService.java new file mode 100644 index 0000000000..cb5e1a930e --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/service/BookService.java @@ -0,0 +1,15 @@ +package com.hexagonal.service; + +import java.util.List; + +import com.hexagonal.domain.Book; + +public interface BookService { + + public void addBook(Book book); + + public Book buyBook(String isbn); + + public List listBooks(); + +} diff --git a/bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java b/bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java new file mode 100644 index 0000000000..c7e660ea36 --- /dev/null +++ b/bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java @@ -0,0 +1,35 @@ +package com.hexagonal.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.hexagonal.domain.Book; +import com.hexagonal.repository.BookRepository; + +@Service +public class BookServiceImpl implements BookService { + + @Autowired + private BookRepository bookRepository; + + @Override + public void addBook(Book book) { + bookRepository.add(book); + + } + + @Override + public Book buyBook(String isbn) { + + return bookRepository.buy(isbn); + } + + @Override + public List listBooks() { + + return bookRepository.list(); + } + +} From 8f22ea5d36d35cd990d3fdf7b561b77add9278c5 Mon Sep 17 00:00:00 2001 From: STS Date: Fri, 3 Jul 2020 23:56:52 +0200 Subject: [PATCH 021/155] change files location --- apache-poi/excelformula/.gitignore | 34 ----------- apache-poi/excelformula/pom.xml | 57 ------------------- .../excelformula/ExcelformulaApplication.java | 13 ----- .../src/main/resources/application.properties | 1 - .../poi/excel/setFormula}/ExcelFormula.java | 4 +- .../setFormula/ExcelFormulaUnitTest.java} | 15 +---- 6 files changed, 4 insertions(+), 120 deletions(-) delete mode 100644 apache-poi/excelformula/.gitignore delete mode 100644 apache-poi/excelformula/pom.xml delete mode 100644 apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java delete mode 100644 apache-poi/excelformula/src/main/resources/application.properties rename apache-poi/{excelformula/src/main/java/com/bealdung/poi/excelformula => src/main/java/com/baeldung/poi/excel/setFormula}/ExcelFormula.java (90%) rename apache-poi/{excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java => src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java} (71%) diff --git a/apache-poi/excelformula/.gitignore b/apache-poi/excelformula/.gitignore deleted file mode 100644 index 719e322c1d..0000000000 --- a/apache-poi/excelformula/.gitignore +++ /dev/null @@ -1,34 +0,0 @@ -HELP.md -mvnw -mvnw.cmd -.mvn -target/ -!.mvn/wrapper/maven-wrapper.jar -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ - -### VS Code ### -.vscode/ diff --git a/apache-poi/excelformula/pom.xml b/apache-poi/excelformula/pom.xml deleted file mode 100644 index 4ea65b5e57..0000000000 --- a/apache-poi/excelformula/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - com.bealdung.poi - excelformula - 0.0.1-SNAPSHOT - excelformula - Demo project for Spring Boot - - 11 - 4.1.2 - 4.13 - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - org.apache.poi - poi-ooxml - ${poi-ooxml.version} - - - junit - junit - ${junit.version} - test - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - diff --git a/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java b/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java deleted file mode 100644 index b857bd4266..0000000000 --- a/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelformulaApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.bealdung.poi.excelformula; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ExcelformulaApplication { - - public static void main(String[] args) { - SpringApplication.run(ExcelformulaApplication.class, args); - } - -} diff --git a/apache-poi/excelformula/src/main/resources/application.properties b/apache-poi/excelformula/src/main/resources/application.properties deleted file mode 100644 index 8b13789179..0000000000 --- a/apache-poi/excelformula/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java b/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java similarity index 90% rename from apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java rename to apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java index 1e2fa5acfe..7bd8d8a035 100644 --- a/apache-poi/excelformula/src/main/java/com/bealdung/poi/excelformula/ExcelFormula.java +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java @@ -1,16 +1,14 @@ -package com.bealdung.poi.excelformula; +package com.baeldung.poi.excel.setFormula; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.springframework.stereotype.Component; import java.io.IOException; import java.util.List; -@Component public class ExcelFormula { XSSFWorkbook excel; public XSSFSheet inserData(List dataList) { diff --git a/apache-poi/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java b/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java similarity index 71% rename from apache-poi/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java rename to apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java index c2385911d0..8daf311149 100644 --- a/apache-poi/excelformula/src/test/java/com/bealdung/poi/excelformula/ExcelformulaApplicationTests.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java @@ -1,26 +1,18 @@ -package com.bealdung.poi.excelformula; +package com.baeldung.poi.excel.setFormula; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.junit.Assert; import org.junit.jupiter.api.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.io.IOException; import java.util.Arrays; import java.util.List; -@RunWith(SpringRunner.class) -@SpringBootTest -class ExcelformulaApplicationTests { - @Autowired - private ExcelFormula excelFormula; - +class ExcelFormulaUnitTest { @Test void givenExcelData_whenSetAndEvaluateFormula() throws IOException { + ExcelFormula excelFormula = new ExcelFormula(); List data = Arrays.asList(2, 5, 10, 15, 7, 9); XSSFSheet sheet = excelFormula.inserData(data); int result = 0; @@ -34,5 +26,4 @@ class ExcelformulaApplicationTests { int resultValue = (int) excelFormula.setFormula(sumFormula); Assert.assertEquals("The results are the same!", resultValue , result); } - } From 5e63ab27a1f0a60271fd77828da003350db98876 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sat, 4 Jul 2020 21:53:43 +0530 Subject: [PATCH 022/155] Refactored test cases to throw generic Exception --- .../AccessPrivateFieldsUnitTest.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java index 5a2a33fa8f..49e1b917b1 100644 --- a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java +++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java @@ -8,7 +8,7 @@ import org.junit.jupiter.api.Test; public class AccessPrivateFieldsUnitTest { @Test - public void whenGetIntegerFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenGetIntegerFields_thenSuccess() throws Exception { Person person = new Person(); Field ageField = person.getClass() @@ -42,7 +42,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenDoAutoboxing_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenDoAutoboxing_thenSuccess() throws Exception { Person person = new Person(); Field pinCodeField = person.getClass() @@ -54,7 +54,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenDoWidening_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenDoWidening_thenSuccess() throws Exception { Person person = new Person(); Field pinCodeField = person.getClass() @@ -66,7 +66,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenGetFloatingTypeFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenGetFloatingTypeFields_thenSuccess() throws Exception { Person person = new Person(); Field heightField = person.getClass() @@ -85,7 +85,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenGetCharacterFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenGetCharacterFields_thenSuccess() throws Exception { Person person = new Person(); Field genderField = person.getClass() @@ -97,7 +97,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenGetBooleanFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenGetBooleanFields_thenSuccess() throws Exception { Person person = new Person(); Field activeField = person.getClass() @@ -109,7 +109,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenGetObjectFields_thenSuccess() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenGetObjectFields_thenSuccess() throws Exception { Person person = new Person(); Field nameField = person.getClass() @@ -121,7 +121,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void givenInt_whenGetStringField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void givenInt_whenGetStringField_thenIllegalArgumentException() throws Exception { Person person = new Person(); Field nameField = person.getClass() .getDeclaredField("name"); @@ -131,7 +131,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void givenInt_whenGetLongField_thenIllegalArgumentException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void givenInt_whenGetLongField_thenIllegalArgumentException() throws Exception { Person person = new Person(); Field contactNumberField = person.getClass() .getDeclaredField("contactNumber"); @@ -141,7 +141,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenFieldNotSetAccessible_thenIllegalAccessException() throws IllegalAccessException, IllegalArgumentException, NoSuchFieldException, NullPointerException { + public void whenFieldNotSetAccessible_thenIllegalAccessException() throws Exception { Person person = new Person(); Field nameField = person.getClass() .getDeclaredField("name"); @@ -150,7 +150,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenAccessingWrongProperty_thenNoSuchFieldException() throws NoSuchFieldException, NullPointerException { + public void whenAccessingWrongProperty_thenNoSuchFieldException() throws Exception { Person person = new Person(); Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass() @@ -158,7 +158,7 @@ public class AccessPrivateFieldsUnitTest { } @Test - public void whenAccessingNullProperty_thenNullPointerException() throws NoSuchFieldException, NullPointerException { + public void whenAccessingNullProperty_thenNullPointerException() throws Exception { Person person = new Person(); Assertions.assertThrows(NullPointerException.class, () -> person.getClass() From 06dcb4ea6d3ad93a624fa103000d3d4ee8946abc Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Fri, 10 Jul 2020 20:06:12 +0530 Subject: [PATCH 023/155] Created new module core-java-reflection-2 --- .../core-java-reflection-2/pom.xml | 45 +++ .../access/privatefields/Person.java | 0 .../AccessPrivateFieldsUnitTest.java | 0 core-java-modules/pom.xml | 291 +++++++++--------- 4 files changed, 191 insertions(+), 145 deletions(-) create mode 100644 core-java-modules/core-java-reflection-2/pom.xml rename core-java-modules/{core-java-reflection => core-java-reflection-2}/src/main/java/com/baeldung/reflection/access/privatefields/Person.java (100%) rename core-java-modules/{core-java-reflection => core-java-reflection-2}/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java (100%) diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml new file mode 100644 index 0000000000..d711dabd1a --- /dev/null +++ b/core-java-modules/core-java-reflection-2/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + core-java-reflection-2 + 0.1.0-SNAPSHOT + core-java-reflection-2 + jar + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + core-java-reflection-2 + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${source.version} + ${target.version} + -parameters + + + + + + + 3.8.0 + 1.8 + 1.8 + + diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatefields/Person.java similarity index 100% rename from core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java rename to core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatefields/Person.java diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java similarity index 100% rename from core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java rename to core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 26c374b51d..272da94f5d 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -1,169 +1,170 @@ - - 4.0.0 - com.baeldung.core-java-modules - core-java-modules - core-java-modules - pom + + 4.0.0 + com.baeldung.core-java-modules + core-java-modules + core-java-modules + pom - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - core-java - - - - - core-java-8 - core-java-8-2 + + core-java + + + + + core-java-8 + core-java-8-2 - - - - - + + + + + - core-java-annotations + core-java-annotations - core-java-arrays-sorting - core-java-arrays-guides - core-java-arrays-multidimensional - core-java-arrays-convert - core-java-arrays-operations-basic - core-java-arrays-operations-advanced - - core-java-collections - core-java-collections-2 - core-java-collections-3 - core-java-collections-array-list - core-java-collections-list - core-java-collections-list-2 - core-java-collections-list-3 - core-java-collections-maps - core-java-collections-maps-2 - core-java-collections-maps-3 - + core-java-arrays-sorting + core-java-arrays-guides + core-java-arrays-multidimensional + core-java-arrays-convert + core-java-arrays-operations-basic + core-java-arrays-operations-advanced - core-java-concurrency-2 - core-java-concurrency-advanced - core-java-concurrency-advanced-2 - core-java-concurrency-advanced-3 - core-java-concurrency-basic - core-java-concurrency-basic-2 - core-java-concurrency-collections + core-java-collections + core-java-collections-2 + core-java-collections-3 + core-java-collections-array-list + core-java-collections-list + core-java-collections-list-2 + core-java-collections-list-3 + core-java-collections-maps + core-java-collections-maps-2 + core-java-collections-maps-3 + - - core-java-date-operations-2 - - + core-java-concurrency-2 + core-java-concurrency-advanced + core-java-concurrency-advanced-2 + core-java-concurrency-advanced-3 + core-java-concurrency-basic + core-java-concurrency-basic-2 + core-java-concurrency-collections - core-java-exceptions - core-java-exceptions-2 + + core-java-date-operations-2 + + - core-java-function + core-java-exceptions + core-java-exceptions-2 - core-java-io - core-java-io-2 - core-java-io-apis - core-java-io-conversions - core-java-io-conversions-2 + core-java-function - core-java-jar - core-java-jndi - - core-java-jvm + core-java-io + core-java-io-2 + core-java-io-apis + core-java-io-conversions + core-java-io-conversions-2 - core-java-lambdas - core-java-lang - core-java-lang-2 - core-java-lang-math - core-java-lang-math-2 - core-java-lang-oop-constructors - core-java-lang-oop-patterns - core-java-lang-oop-generics - core-java-lang-oop-modifiers - core-java-lang-oop-types - core-java-lang-oop-inheritance - core-java-lang-oop-methods - core-java-lang-oop-others - core-java-lang-operators - core-java-lang-syntax - core-java-lang-syntax-2 + core-java-jar + core-java-jndi + + core-java-jvm - core-java-networking - core-java-networking-2 - core-java-nio - core-java-nio-2 + core-java-lambdas + core-java-lang + core-java-lang-2 + core-java-lang-math + core-java-lang-math-2 + core-java-lang-oop-constructors + core-java-lang-oop-patterns + core-java-lang-oop-generics + core-java-lang-oop-modifiers + core-java-lang-oop-types + core-java-lang-oop-inheritance + core-java-lang-oop-methods + core-java-lang-oop-others + core-java-lang-operators + core-java-lang-syntax + core-java-lang-syntax-2 - core-java-optional - + core-java-networking + core-java-networking-2 + core-java-nio + core-java-nio-2 - core-java-perf + core-java-optional + - core-java-reflection + core-java-perf - core-java-security - core-java-security-2 - core-java-streams - core-java-streams-2 - core-java-streams-3 - core-java-string-algorithms - core-java-string-algorithms-2 - core-java-string-algorithms-3 - core-java-string-apis - core-java-string-conversions - core-java-string-conversions-2 - core-java-string-operations - core-java-string-operations-2 - core-java-strings - core-java-sun + core-java-reflection + core-java-reflection-2 - core-java-regex - + core-java-security + core-java-security-2 + core-java-streams + core-java-streams-2 + core-java-streams-3 + core-java-string-algorithms + core-java-string-algorithms-2 + core-java-string-algorithms-3 + core-java-string-apis + core-java-string-conversions + core-java-string-conversions-2 + core-java-string-operations + core-java-string-operations-2 + core-java-strings + core-java-sun - - pre-jpms - + core-java-regex + - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - + + pre-jpms + - - - - org.junit.jupiter - junit-jupiter - ${junit-jupiter.version} - test - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - test - - - + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + - - 2.22.2 - 5.6.2 - + + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + test + + + + + + 2.22.2 + 5.6.2 + From a86a226237ce6fb412d555700c1820750a23c84d Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Fri, 10 Jul 2020 20:27:38 +0530 Subject: [PATCH 024/155] Revert "Created new module core-java-reflection-2" This reverts commit 06dcb4ea6d3ad93a624fa103000d3d4ee8946abc. --- .../core-java-reflection-2/pom.xml | 45 --- .../access/privatefields/Person.java | 0 .../AccessPrivateFieldsUnitTest.java | 0 core-java-modules/pom.xml | 291 +++++++++--------- 4 files changed, 145 insertions(+), 191 deletions(-) delete mode 100644 core-java-modules/core-java-reflection-2/pom.xml rename core-java-modules/{core-java-reflection-2 => core-java-reflection}/src/main/java/com/baeldung/reflection/access/privatefields/Person.java (100%) rename core-java-modules/{core-java-reflection-2 => core-java-reflection}/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java (100%) diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml deleted file mode 100644 index d711dabd1a..0000000000 --- a/core-java-modules/core-java-reflection-2/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - core-java-reflection-2 - 0.1.0-SNAPSHOT - core-java-reflection-2 - jar - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - ../ - - - - core-java-reflection-2 - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${source.version} - ${target.version} - -parameters - - - - - - - 3.8.0 - 1.8 - 1.8 - - diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java similarity index 100% rename from core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatefields/Person.java rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java similarity index 100% rename from core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 272da94f5d..26c374b51d 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -1,170 +1,169 @@ - - 4.0.0 - com.baeldung.core-java-modules - core-java-modules - core-java-modules - pom + + 4.0.0 + com.baeldung.core-java-modules + core-java-modules + core-java-modules + pom - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + - - core-java - - - - - core-java-8 - core-java-8-2 + + core-java + + + + + core-java-8 + core-java-8-2 - - - - - + + + + + - core-java-annotations + core-java-annotations - core-java-arrays-sorting - core-java-arrays-guides - core-java-arrays-multidimensional - core-java-arrays-convert - core-java-arrays-operations-basic - core-java-arrays-operations-advanced + core-java-arrays-sorting + core-java-arrays-guides + core-java-arrays-multidimensional + core-java-arrays-convert + core-java-arrays-operations-basic + core-java-arrays-operations-advanced + + core-java-collections + core-java-collections-2 + core-java-collections-3 + core-java-collections-array-list + core-java-collections-list + core-java-collections-list-2 + core-java-collections-list-3 + core-java-collections-maps + core-java-collections-maps-2 + core-java-collections-maps-3 + - core-java-collections - core-java-collections-2 - core-java-collections-3 - core-java-collections-array-list - core-java-collections-list - core-java-collections-list-2 - core-java-collections-list-3 - core-java-collections-maps - core-java-collections-maps-2 - core-java-collections-maps-3 - + core-java-concurrency-2 + core-java-concurrency-advanced + core-java-concurrency-advanced-2 + core-java-concurrency-advanced-3 + core-java-concurrency-basic + core-java-concurrency-basic-2 + core-java-concurrency-collections - core-java-concurrency-2 - core-java-concurrency-advanced - core-java-concurrency-advanced-2 - core-java-concurrency-advanced-3 - core-java-concurrency-basic - core-java-concurrency-basic-2 - core-java-concurrency-collections + + core-java-date-operations-2 + + - - core-java-date-operations-2 - - + core-java-exceptions + core-java-exceptions-2 - core-java-exceptions - core-java-exceptions-2 + core-java-function - core-java-function + core-java-io + core-java-io-2 + core-java-io-apis + core-java-io-conversions + core-java-io-conversions-2 - core-java-io - core-java-io-2 - core-java-io-apis - core-java-io-conversions - core-java-io-conversions-2 + core-java-jar + core-java-jndi + + core-java-jvm - core-java-jar - core-java-jndi - - core-java-jvm + core-java-lambdas + core-java-lang + core-java-lang-2 + core-java-lang-math + core-java-lang-math-2 + core-java-lang-oop-constructors + core-java-lang-oop-patterns + core-java-lang-oop-generics + core-java-lang-oop-modifiers + core-java-lang-oop-types + core-java-lang-oop-inheritance + core-java-lang-oop-methods + core-java-lang-oop-others + core-java-lang-operators + core-java-lang-syntax + core-java-lang-syntax-2 - core-java-lambdas - core-java-lang - core-java-lang-2 - core-java-lang-math - core-java-lang-math-2 - core-java-lang-oop-constructors - core-java-lang-oop-patterns - core-java-lang-oop-generics - core-java-lang-oop-modifiers - core-java-lang-oop-types - core-java-lang-oop-inheritance - core-java-lang-oop-methods - core-java-lang-oop-others - core-java-lang-operators - core-java-lang-syntax - core-java-lang-syntax-2 + core-java-networking + core-java-networking-2 + core-java-nio + core-java-nio-2 - core-java-networking - core-java-networking-2 - core-java-nio - core-java-nio-2 + core-java-optional + - core-java-optional - + core-java-perf - core-java-perf + core-java-reflection - core-java-reflection - core-java-reflection-2 + core-java-security + core-java-security-2 + core-java-streams + core-java-streams-2 + core-java-streams-3 + core-java-string-algorithms + core-java-string-algorithms-2 + core-java-string-algorithms-3 + core-java-string-apis + core-java-string-conversions + core-java-string-conversions-2 + core-java-string-operations + core-java-string-operations-2 + core-java-strings + core-java-sun - core-java-security - core-java-security-2 - core-java-streams - core-java-streams-2 - core-java-streams-3 - core-java-string-algorithms - core-java-string-algorithms-2 - core-java-string-algorithms-3 - core-java-string-apis - core-java-string-conversions - core-java-string-conversions-2 - core-java-string-operations - core-java-string-operations-2 - core-java-strings - core-java-sun + core-java-regex + - core-java-regex - + + pre-jpms + - - pre-jpms - + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - + + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + test + + + - - - - org.junit.jupiter - junit-jupiter - ${junit-jupiter.version} - test - - - org.junit.vintage - junit-vintage-engine - ${junit-jupiter.version} - test - - - - - - 2.22.2 - 5.6.2 - + + 2.22.2 + 5.6.2 + From 2fa700d339d9a9d2ab499c26875559dffdd24c4c Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Fri, 10 Jul 2020 20:47:46 +0530 Subject: [PATCH 025/155] Added new module core-java-reflection-2 --- .../core-java-reflection-2/README.MD | 3 ++ .../core-java-reflection-2/pom.xml | 44 +++++++++++++++++++ .../access/privatefields/Person.java | 0 .../AccessPrivateFieldsUnitTest.java | 0 core-java-modules/pom.xml | 1 + 5 files changed, 48 insertions(+) create mode 100644 core-java-modules/core-java-reflection-2/README.MD create mode 100644 core-java-modules/core-java-reflection-2/pom.xml rename core-java-modules/{core-java-reflection => core-java-reflection-2}/src/main/java/com/baeldung/reflection/access/privatefields/Person.java (100%) rename core-java-modules/{core-java-reflection => core-java-reflection-2}/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java (100%) diff --git a/core-java-modules/core-java-reflection-2/README.MD b/core-java-modules/core-java-reflection-2/README.MD new file mode 100644 index 0000000000..7658851a4d --- /dev/null +++ b/core-java-modules/core-java-reflection-2/README.MD @@ -0,0 +1,3 @@ +## Relevant Articles + +- [Reading the Value of 'private' Fields from a Different Class in Java](https://www.baeldung.com/) \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml new file mode 100644 index 0000000000..17cad52271 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + core-java-reflection-2 + 0.1.0-SNAPSHOT + core-java-reflection-2 + jar + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + core-java-reflection-2 + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${source.version} + ${target.version} + -parameters + + + + + + + 3.8.0 + 1.8 + 1.8 + + \ No newline at end of file diff --git a/core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatefields/Person.java similarity index 100% rename from core-java-modules/core-java-reflection/src/main/java/com/baeldung/reflection/access/privatefields/Person.java rename to core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/access/privatefields/Person.java diff --git a/core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java similarity index 100% rename from core-java-modules/core-java-reflection/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java rename to core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/access/privatefields/AccessPrivateFieldsUnitTest.java diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index d01a7cc792..4f26c194ee 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -110,6 +110,7 @@ core-java-perf core-java-reflection + core-java-reflection-2 core-java-security core-java-security-2 From 3e31cb49b16682206ba189db0233d1e5bc0b43fd Mon Sep 17 00:00:00 2001 From: STS Date: Sat, 11 Jul 2020 10:31:02 +0200 Subject: [PATCH 026/155] changes after adding excel file --- .../poi/excel/setFormula/ExcelFormula.java | 32 +++++------- .../src/main/resources/SetFormulaTest.xlsx | Bin 0 -> 8014 bytes .../setFormula/ExcelFormulaUnitTest.java | 46 +++++++++++++----- 3 files changed, 45 insertions(+), 33 deletions(-) create mode 100644 apache-poi/src/main/resources/SetFormulaTest.xlsx diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java b/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java index 7bd8d8a035..8b1ca5a89a 100644 --- a/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java @@ -1,34 +1,26 @@ package com.baeldung.poi.excel.setFormula; -import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; -import java.util.List; public class ExcelFormula { - XSSFWorkbook excel; - public XSSFSheet inserData(List dataList) { - excel = new XSSFWorkbook(); - XSSFSheet sheet = excel.createSheet(); - int rowNum =0 ; - for (Integer data : dataList){ - sheet.createRow(rowNum++).createCell(0).setCellValue(data); - } - return sheet; - } - public double setFormula(String formula) throws IOException { - XSSFSheet sheet = excel.getSheetAt(0); + public double setFormula(String fileLocation, XSSFWorkbook wb, String formula) throws IOException { + XSSFSheet sheet = wb.getSheetAt(0); int lastCellNum = sheet.getRow(0).getLastCellNum(); - XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum + 1); + XSSFCell formulaCell = sheet.getRow(0).createCell(lastCellNum); formulaCell.setCellFormula(formula); - XSSFFormulaEvaluator formulaEvaluator = excel.getCreationHelper().createFormulaEvaluator(); - CellValue evaluate = formulaEvaluator.evaluate(formulaCell); - if(excel != null) - excel.close(); - return evaluate.getNumberValue(); + XSSFFormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator(); + formulaEvaluator.evaluateFormulaCell(formulaCell); + FileOutputStream fileOut = new FileOutputStream(new File(fileLocation)); + wb.write(fileOut); + wb.close(); + fileOut.close(); + return formulaCell.getNumericCellValue(); } } diff --git a/apache-poi/src/main/resources/SetFormulaTest.xlsx b/apache-poi/src/main/resources/SetFormulaTest.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..a0fe73f0ebe74ad3ca9020e685c4a6f0564687e5 GIT binary patch literal 8014 zcmeHM1zS|x8XiEpX6O`YknWc5PHB)35u{;gq`Nz%YmhEMN?J;gM!F>=grT|Px%XVp z@tpe$?pgbJ_L|wV-|yM8_WOPBTJKU*M0kJ)Kmwou002rrp=R%x3LF4{@&Ew91)#ti zNZQ-ESlYRmXn8nTIvcUNzp{Ol{{WsL7XS~t|DX1MJOUMoLn__uKxwGljpPPP#A2-& z3eQ16KTZn+h3T5S*%X_{mx((OTxgA09{x+d8ndx4&LUhn!@SdYHesc0klD0YUAW3~ zh1N#1H<3*z@%U+lniKBG_zUp0bKlRO*Uln!2Go-4R46hEqx!od>rg@A$g;Vg=%?@S zHBt?DG8zD(1>=FGZHg-z>7JOp+3&@upVHx1kTK#fT~@(^!L2R!F{HUPPjPUWTITbyR1I*9 z^(hG|ZV_1sfk?W)exI`5lG#Ni+?0go!P}7PCcfOSiDQ|5GbzQpn4)0tMM(p5NfM2{w*bmmik_69=Lyq(CaVF9 zVsgB5D3wTy&NQ#UqU*UTc<-PplJT3l19~RV%Bdr5AK|tDGmc8$KycwRst}{gi|X6L zE;+#-BMRLjf_@Ug_@j`4#)5H&ErfU6*4|{%g+vAzeGiosn+Hz`qwa-rh4-|s^(DW| zjOCUy(wrRFEpxXOf$d|d1>U_DOR<(CR7(zL2@mPWqLu9&x)>2TPRI$?xgv8kjVL@$;H<7$(4n_lKY#1 zmK{6?LznthBPct2T>lQInP9l`n|I|x%p+b2G$?-nXVvE1nT|CAsk|jczKaYUl-Px- zd0c1aFf2EKanR~a<{400bFjCT0OuS1yvR-q^b=N-+?IT`oe^rN_NdB>GU&xZ$ZqS9 zv7BIZ0u7d)+D+10pF95aCq=L<)$kEs+QWWFVJQuD!ihZfl_LcvS+YCRdy`9&nko|I zukKA3?+B5~7?I{9Xnp*xs%!XGNUHcatsoWqQFlRKk}JXUC~=KJSfyS!Dv=W;##kfj zI8ld~vIb99DRLsO3DE!)r6^&MjLU=fiK%7+F3`5lw%gvL>hDF<2M z_yUt{oCrb(iL+I`?A2{aQ|o%El>1xXh{c|YJ&l^yG^g+;dQOwyMY@0Xi04#^Zh&J( zo11F5!!a()g<_Z}tHMP(6>2TmEwE$wP*nQ?zaL&r@GHVENPnIb^S2|4!!w;J4WLwxfKKx=E%Wu}pqa61Nz&ewB@y%ll-VqE zXCzECO9ou41BZRY(|SZcDB$@aP=)#0l2)nZQ>GjcS)I>5dqxv6WyF$9CxoSiy&8o_ zzd!1Z$flc@te)Hk;5X66XWFqzQS{qI&`8lz&<{kLQb5;-s~@WNO!}HRyvVk_Ur^g4 zTtNS!3)f6k5v?~_h9C*fEL#>w{5p*E!<-5ip$@3)q6REGIvy_2gNjrnQ1ZNH+^1LZZfq8Pbi!*G{a_ucBOm?vuV{vTlYPvZK}@y;{wdpe}(uM<+|v zl4QjEj47`s{i#lHNd;nZU7BDb7fm>3H=U{6j*-8z)xTlavHBd$1{@aWHz3A>nqc>0(b|o*%&fpuH=eBIeNM5#93;T4GdxaaN4VJOB8S%t}tsInU3Fdif z87anSZD(rpNH{yRw>FK+)|vwypXf(sso!qeW!ODp(d*_cxcvTow~cQ(k(-chF}ln- zNK-|3!VN;g+z{Ru_n`8yG7?8Xny*Ni&8*h3X$Sq`| zu(geQsl*`@g_Tr>doi`RW?b@Ff2el&3i`u|NdbxagAe@XZo)m_;61e-MBx{$_-ETG zO>8OSI!oaZm_7}@2xqC#A)zR2o0r2bp4B9ir`~Kk75hv8{Jm!10*dc}$s&ki1)yQ> z_56kJt#9qd#%f3yTI**Ic|6a`{b%-PX86J0mt03^NpsNYqd;*KV{X{zRi8*zl7>$| zF0Tgico$6UdSD_{iGgSbS4mpdkk1?h7Vs@T?8M+NowSJ;q>!?y#bHAB6C{;%sdzW_ zqYkTG007iNxwsxsBymnI$igvD1ICwl_ZaCv&*ln|1y4*f}}E7rPs)-HFJe&l{s+gc#Dl zlACy6&%H76+rK&9$RvzyuU>x_bAJ}9>U(+VECi%8a9_PljrH@oy10D$=I(Bh8vT7@ zJ_7j@8jh_|ZSVarrX0h{9$gkO*b{!!=0ucc-^D<)jcJFG0{~;AM=!fwYj)ooFrq|Z zx_kKcue4AUIg2w>n}nMoH1`u7)J}eV&E&*9(%tRB*?^rh>iPvUD8|-2lz~HH;mw$s zUigRw(X+rU*9aW{V*aiV@nf@;eJOK`bUjCV4~dJS>cSoDa7!Y?rf4OdOldU6twVc& zslm~Yg65A#mRL%LN?%Qjcw11d28&Hf_=c6O_6@yYRkP(1km8skZ;zC+pnlgOCo5Pv zhA8D3!RUNtKK$)=n1-8Zla4cvDXYHYGAGlyE7yA!e$2S=@}4~wI?KOMqXTgQXM`im z=D(=AfVj=R3d11hjxd`2_qGTaECA$ zs1_3p`BYR#Srr?ehSiHpDDou+rG$V;)`f-63KCDFTp=iB;;JoXm%Mn~BqMwv8%C;< zdVjhWjZZxScCF%zp`U9&84Zi5`!}ncIpT*7?+&G1(E6>Y@f^6Z{~-(CkYsa zs}v(~fcRY*!WSyD?jDoA$mf=FgiMP8m-L-j;*y)9$sR0XaONl-$?ZIw(Jw5iGf=xw zVyaNphRz@l<=A4aF2(lskHTe_@Bs_cmP-|oV^Bj8a$jzZaQNenB*)=jg3H-AYatYj zY3iVPKmT?DUMm^>rE<2YFkXz zNA6}aosdBC!$>MPcXbw!j9(bpl)1*0PCs^(neqt^$W>=T;wqKz+v8;B5whng%U%x< zJC&;LvWJj7JL}og@!bIn+F1JQRx)X?K~yQOW>DQ6kb4S{w>zC5H>1&dd&z;AuWA!F zlz3P0-!Yx=P#FrGCe<%`;diVD^N2EQXZUt(OtmSL?Sj7+#eAEA_;l#+y4pbVs>2v6 zujZ^$;j(1MrSFcV8>)O>ho{Qg5y~*La-I1XRfIvX*{9~Wu-UQT#@`W6BE9v5kS6J$ zjplBgwTx&mVYCz(19?3Ijd%DA0)1@C|tHpCNX|HeN2-5 ze0lH7SSknmsnQcClhVz_H9_4hAb3P27^mkH;nN&J~gB)NmR%MXWMgA5c*<{7%8su-e5D$%$^EF- zBB+voj<;SrFg%w>C$6JHmtM9h2dqPA&R|VwQgNTnWTM0MF_JA9}A(oQFn{z zdtl;ttDiufJrT(8L}Si$8zVfYO282ZIqRg}v>M*XP4N?_WbD$(;Avc9iI4vsdrN9x zUD44M{aZ%$`qw@ZDV6sbr(hQE;10v;q&6`Fv;5hZC!bqJKXH|AESu9| zxZ|-@KI#^bW66no=B=a4<*NlP(EcjY;lb80t7~a-O`mCvwsy^4TV=a#hNT@z{}L!u z(!jGGK4&V69=-jj!CfL?)B1CUTnqkjKT6u+;mUcm8-RZi{Mebbf+7441MA4O)nt2zHDy$2ySw^S`kT!gSK9cSp~hH!#nyDnOTA&2TsJM=-iPJI8cnTh zugfJIK9X0P8aAZpr}fdZJv8)}m1ynBxU7!4UXlZXLrs>PMVwkmM98FY0>|6?VhaTgr^M$L$(u>TJIsDIZ|*skkq+1$09drCvi-!@t;f)-w59>Me;A z%tgSc2SNYnMg0CuY~%Q(wby*~hL`)5l)Mpzpvm{R@m{s?&3rt>2c$NH=gG~>x6K!i z(P(gAuA9GBAcN~|xVsR4<)joh2uDB$s>Wea*Ow1(3?5wx*z8omb+!syc%NEhofVw< z;*B5*4cpL3WDtUQX0(hlv&GLVd?Y?zfrn#f;en3_L#+8zoWH$ydvoT*?ciuf22Teh7zKf2 zgjcGbn{&2FzR$vq#lZa*R7ZYM%(d;ko_tyObZ&2!7B_}DtNabC@S4wjFRA3w`_a?9 z`9?a)5jF>XsCBNLN8%hd<=%9V$mCc~(}$xA?9bRULlEi9vJG(dNRs#E(ACe<2?x&t z_+NXUzrU~F`@h)aSJb}sW71@t({{n|4 B-9P{U literal 0 HcmV?d00001 diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java index 8daf311149..990b93fcbb 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java @@ -2,28 +2,48 @@ package com.baeldung.poi.excel.setFormula; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Assert; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.io.File; +import java.io.FileInputStream; import java.io.IOException; -import java.util.Arrays; -import java.util.List; +import java.net.URISyntaxException; +import java.nio.file.Paths; class ExcelFormulaUnitTest { + private static String FILE_NAME = "SetFormulaTest.xlsx"; + private String fileLocation; + private ExcelFormula excelFormula; + + @BeforeEach + public void setup() throws URISyntaxException { + fileLocation = Paths.get(ClassLoader.getSystemResource(FILE_NAME).toURI()).toString(); + excelFormula = new ExcelFormula(); + } + @Test void givenExcelData_whenSetAndEvaluateFormula() throws IOException { - ExcelFormula excelFormula = new ExcelFormula(); - List data = Arrays.asList(2, 5, 10, 15, 7, 9); - XSSFSheet sheet = excelFormula.inserData(data); - int result = 0; + FileInputStream inputStream = new FileInputStream(new File(fileLocation)); + XSSFWorkbook wb = new XSSFWorkbook(inputStream); + XSSFSheet sheet = wb.getSheetAt(0); + double resultColumnA = 0; + double resultColumnB = 0; for (int row = 0; row <= sheet.getLastRowNum(); row++) { - result += sheet.getRow(row).getCell(0).getNumericCellValue(); + resultColumnA += sheet.getRow(row).getCell(0).getNumericCellValue(); + resultColumnB += sheet.getRow(row).getCell(1).getNumericCellValue(); } - String colName = CellReference.convertNumToColString(0); - String startCell = colName + 1; - String stopCell = colName + (sheet.getLastRowNum() + 1); - String sumFormula = String.format("SUM(%s:%s)", startCell, stopCell); - int resultValue = (int) excelFormula.setFormula(sumFormula); - Assert.assertEquals("The results are the same!", resultValue , result); + String colNameA = CellReference.convertNumToColString(0); + String colNameB = CellReference.convertNumToColString(1); + String startCellA = colNameA + 1; + String stopCellA = colNameA + (sheet.getLastRowNum() + 1); + String sumFormulaForColumnA = String.format("SUM(%s:%s)", startCellA, stopCellA); + String startCellB = colNameB + 1; + String stopCellB = colNameB + (sheet.getLastRowNum() + 1); + String sumFormulaForColumnB = String.format("SUM(%s:%s)", startCellB, stopCellB); + double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB); + Assert.assertEquals(resultValue, resultColumnA - resultColumnB, 0d); } } From 748c9cf1e450e81e80b67180cde7167de379b953 Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sun, 12 Jul 2020 12:28:38 +0530 Subject: [PATCH 027/155] Removed README.MD --- .../core-java-reflection-2/README.MD | 3 - .../core-java-reflection-2/pom.xml | 80 +++++++++---------- 2 files changed, 40 insertions(+), 43 deletions(-) delete mode 100644 core-java-modules/core-java-reflection-2/README.MD diff --git a/core-java-modules/core-java-reflection-2/README.MD b/core-java-modules/core-java-reflection-2/README.MD deleted file mode 100644 index 7658851a4d..0000000000 --- a/core-java-modules/core-java-reflection-2/README.MD +++ /dev/null @@ -1,3 +0,0 @@ -## Relevant Articles - -- [Reading the Value of 'private' Fields from a Different Class in Java](https://www.baeldung.com/) \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml index 17cad52271..ea76ee8c98 100644 --- a/core-java-modules/core-java-reflection-2/pom.xml +++ b/core-java-modules/core-java-reflection-2/pom.xml @@ -1,44 +1,44 @@ - 4.0.0 - core-java-reflection-2 - 0.1.0-SNAPSHOT - core-java-reflection-2 - jar - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - ../ - + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + core-java-reflection-2 + 0.1.0-SNAPSHOT + core-java-reflection-2 + jar + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + ../ + + + + core-java-reflection-2 + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${source.version} + ${target.version} + -parameters + + + + - - core-java-reflection-2 - - - src/main/resources - true - - - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${source.version} - ${target.version} - -parameters - - - - - - - 3.8.0 - 1.8 - 1.8 - + + 3.8.0 + 1.8 + 1.8 + \ No newline at end of file From 64dc02f18fdbde9e728083aef09cf7318f9145cf Mon Sep 17 00:00:00 2001 From: mdhtr Date: Sun, 12 Jul 2020 23:29:55 +0200 Subject: [PATCH 028/155] Examples for the second version of the article --- .../JacksonDeserializationExample.java | 40 ------------------ .../hydrajsonld/HydraJsonldExamplePerson.java | 15 ------- .../JacksonJsonLdSerializationExample.java | 25 ----------- .../JacksonJsonldExamplePerson.java | 17 -------- .../JacksonDeserializationUnitTest.java | 41 ++++++++++++++++++ .../jsonldjava/jackson/Person.java} | 4 +- .../HydraJsonldSerializationUnitTest.java} | 37 +++++++++++----- .../JacksonJsonLdSerializationUnitTest.java | 42 +++++++++++++++++++ 8 files changed, 112 insertions(+), 109 deletions(-) delete mode 100644 json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java delete mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java delete mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java delete mode 100644 json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java create mode 100644 json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java rename json-2/src/{main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java => test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java} (88%) rename json-2/src/{main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java => test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java} (52%) create mode 100644 json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java diff --git a/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java b/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java deleted file mode 100644 index b80769b408..0000000000 --- a/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationExample.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.jsonld.deserialization.jsonldjava.jackson; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.jsonldjava.core.JsonLdOptions; -import com.github.jsonldjava.core.JsonLdProcessor; -import com.github.jsonldjava.utils.JsonUtils; - -public class JacksonDeserializationExample { - public static void main(String[] args) throws IOException { - String exampleJsonld ="{" + - " \"@context\": {" + - " \"@vocab\": \"http://schema.org/\"," + - " \"knows\": {" + - " \"@type\": \"@id\"" + - " }" + - " }," + - " \"@type\": \"Person\"," + - " \"@id\": \"http://example.com/person/1234\"," + - " \"name\": \"Example Name\"," + - " \"knows\": \"http://example.com/person/2345\"" + - "}"; - - Object jsonObject = JsonUtils.fromString(exampleJsonld); - Object compact = JsonLdProcessor.compact(jsonObject, new HashMap(), new JsonLdOptions()); - String compactContent = JsonUtils.toString(compact); - - System.out.println(JsonUtils.toPrettyString(compact)); - - ObjectMapper objectMapper = new ObjectMapper(); - JacksonExamplePerson person = objectMapper.readValue(compactContent, JacksonExamplePerson.class); - - System.out.println(person.id); - System.out.println(person.name); - System.out.println(person.knows.id); - } -} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java deleted file mode 100644 index 16b2199a73..0000000000 --- a/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldExamplePerson.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.jsonld.serialization.hydrajsonld; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import de.escalon.hypermedia.hydra.mapping.Expose; -import de.escalon.hypermedia.hydra.mapping.Vocab; - -@Vocab("http://example.com/vocab/") -@Expose("person") -public class HydraJsonldExamplePerson { - @JsonProperty("@id") - public String id; - @Expose("fullName") - public String name; -} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java deleted file mode 100644 index 6a1acee1b8..0000000000 --- a/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationExample.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.jsonld.serialization.jacksonjsonld; - -import java.io.IOException; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import ioinformarics.oss.jackson.module.jsonld.HydraCollection; -import ioinformarics.oss.jackson.module.jsonld.JsonldGraph; -import ioinformarics.oss.jackson.module.jsonld.JsonldModule; -import ioinformarics.oss.jackson.module.jsonld.JsonldResource; - -public class JacksonJsonLdSerializationExample { - public static void main(String[] args) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.registerModule(new JsonldModule()); - - JacksonJsonldExamplePerson person = new JacksonJsonldExamplePerson(); - - JsonldResource jsonldResource = JsonldResource.Builder.create() - .build(person); - - System.out.println(objectMapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(jsonldResource)); - } -} diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java b/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java deleted file mode 100644 index a3161ba1d3..0000000000 --- a/json-2/src/main/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonldExamplePerson.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.jsonld.serialization.jacksonjsonld; - -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldId; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldLink; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldNamespace; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldProperty; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType; - -@JsonldNamespace(name = "s", uri = "http://schema.org/") -@JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345") -@JsonldType("s:Person") -class JacksonJsonldExamplePerson { - @JsonldId - public String id = "http://example.com/person/1234"; - @JsonldProperty("s:name") - public String name = "Example Name"; -} diff --git a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java new file mode 100644 index 0000000000..35a2613957 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.jsonld.deserialization.jsonldjava.jackson; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.IOException; +import java.util.HashMap; + +import org.junit.jupiter.api.Test; + +import com.baeldung.jsonld.deserialization.jsonldjava.jackson.Person.Link; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.jsonldjava.core.JsonLdOptions; +import com.github.jsonldjava.core.JsonLdProcessor; +import com.github.jsonldjava.utils.JsonUtils; + +public class JacksonDeserializationUnitTest { + + @Test + void givenAJsonLdObject_whenCompactIsUsedWithEmptyContext_thenItCanBeDeserializedIntoAJacksonAnnotatedJavaObject() throws IOException { + String inputJsonLd = "{\"@context\":{\"@vocab\":\"http://schema.org/\",\"knows\":{\"@type\":\"@id\"}},\"@type\":\"Person\",\"@id\":\"http://example.com/person/1234\",\"name\":\"Example Name\",\"knows\":\"http://example.com/person/2345\"}"; + + Object jsonObject = JsonUtils.fromString(inputJsonLd); + Object compact = JsonLdProcessor.compact(jsonObject, new HashMap(), new JsonLdOptions()); + String compactContent = JsonUtils.toString(compact); + + assertEquals("{\"@id\":\"http://example.com/person/1234\",\"@type\":\"http://schema.org/Person\",\"http://schema.org/knows\":{\"@id\":\"http://example.com/person/2345\"},\"http://schema.org/name\":\"Example Name\"}", compactContent); + + ObjectMapper objectMapper = new ObjectMapper(); + Person person = objectMapper.readValue(compactContent, Person.class); + + Person expectedPerson = new Person(); + expectedPerson.id = "http://example.com/person/1234"; + expectedPerson.name = "Example Name"; + expectedPerson.knows = new Link(); + expectedPerson.knows.id = "http://example.com/person/2345"; + + assertEquals(expectedPerson.id, person.id); + assertEquals(expectedPerson.name, person.name); + assertEquals(expectedPerson.knows.id, person.knows.id); + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java similarity index 88% rename from json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java rename to json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java index 2e9f38e665..0cb6d43336 100644 --- a/json-2/src/main/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonExamplePerson.java +++ b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) -public class JacksonExamplePerson { +public class Person { @JsonProperty("@id") public String id; @JsonProperty("http://schema.org/name") @@ -12,7 +12,7 @@ public class JacksonExamplePerson { @JsonProperty("http://schema.org/knows") public Link knows; - public class Link { + public static class Link { @JsonProperty("@id") public String id; } diff --git a/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java similarity index 52% rename from json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java rename to json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java index 3d3531b0b5..e5d1e35236 100644 --- a/json-2/src/main/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationExample.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java @@ -1,8 +1,12 @@ package com.baeldung.jsonld.serialization.hydrajsonld; -import java.io.IOException; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; @@ -11,23 +15,36 @@ import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; +import de.escalon.hypermedia.hydra.mapping.Expose; +import de.escalon.hypermedia.hydra.mapping.Vocab; import de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer; -public class HydraJsonldSerializationExample { - public static void main(String[] args) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.registerModule(getJacksonHydraSerializerModule()); +public class HydraJsonldSerializationUnitTest { + @Vocab("http://example.com/vocab/") + @Expose("person") + static class Person { + @JsonProperty("@id") + public String id; + @Expose("fullName") + public String name; + } - HydraJsonldExamplePerson person = new HydraJsonldExamplePerson(); + @Test + void givenAHydraJsonldAnnotatedObject_whenJacksonHydraSerializerIsUsed_thenAJsonLdDocumentIsGenerated() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(getJacksonHydraSerializerModule()); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + Person person = new Person(); person.id = "http://example.com/person/1234"; person.name = "Example Name"; - System.out.println(mapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(person)); + String personJsonLd = objectMapper.writeValueAsString(person); + + assertEquals("{\"@context\":{\"@vocab\":\"http://example.com/vocab/\",\"name\":\"fullName\"},\"@type\":\"person\",\"name\":\"Example Name\",\"@id\":\"http://example.com/person/1234\"}", personJsonLd); } - public static SimpleModule getJacksonHydraSerializerModule() { + static SimpleModule getJacksonHydraSerializerModule() { return new SimpleModule() { @Override diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java new file mode 100644 index 0000000000..b539c73608 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.jsonld.serialization.jacksonjsonld; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +import ioinformarics.oss.jackson.module.jsonld.JsonldModule; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldId; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldLink; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldNamespace; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldProperty; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldResource; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType; + +public class JacksonJsonLdSerializationUnitTest { + @JsonldResource + @JsonldNamespace(name = "s", uri = "http://schema.org/") + @JsonldType("s:Person") + @JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345") + static class Person { + @JsonldId + public String id = "http://example.com/person/1234"; + @JsonldProperty("s:name") + public String name = "Example Name"; + } + + @Test + void givenAJacksonJsonldAnnotatedObject_whenJsonldModuleIsUsed_thenAJsonLdDocumentIsGenerated() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.registerModule(new JsonldModule()); + + Person person = new Person(); + String personJsonLd = objectMapper.writeValueAsString(person); + + assertEquals( + "{\"@type\":\"s:Person\",\"@context\":{\"s\":\"http://schema.org/\",\"name\":\"s:name\",\"knows\":{\"@id\":\"s:knows\",\"@type\":\"@id\"}},\"name\":\"Example Name\",\"@id\":\"http://example.com/person/1234\",\"knows\":\"http://example.com/person/2345\"}", + personJsonLd); + } +} From 793db9f42b2e8cb3fde61072ee8f9a99d633745e Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Mon, 13 Jul 2020 02:19:13 +0200 Subject: [PATCH 029/155] Added exception handling examples --- .../exceptionhandling/ExceptionHandling.kt | 83 +++++++++++++++++++ .../ExceptionHandlingUnitTest.kt | 46 ++++++++++ 2 files changed, 129 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt new file mode 100644 index 0000000000..137a303edb --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt @@ -0,0 +1,83 @@ +package com.baeldung.exceptionhandling + +import java.io.IOException + +class ExceptionHandling { + + fun tryCatchBlock(): Int? { + try { + val message = "Welcome to Kotlin Tutorials" + return message.toInt() + } catch (exception: NumberFormatException) { + println("NumberFormatException in the code") + return null + } + } + + fun tryCatchExpression(): Int? { + val number = try { + val message = "Welcome to Kotlin Tutorials" + message.toInt() + } catch (exception: NumberFormatException) { + println("NumberFormatException in the code") + null + } + return number + } + + fun multipleCatchBlock(): Int? { + return try { + val result = 25 / 0 + return result + } catch (exception: NumberFormatException) { + println("NumberFormatException in the code") + null + } catch (exception: ArithmeticException) { + println("ArithmeticException in the code") + null + } catch (exception: Exception) { + println("Exception in the code") + null + } + } + + fun nestedTryCatchBlock(): Int? { + return try { + val firstNumber = 50 / 2 * 0 + try { + val secondNumber = 100 / firstNumber + secondNumber + } catch (exception: ArithmeticException) { + println("ArithmeticException in the code") + null + } + } catch (exception: NumberFormatException) { + println("NumberFormatException in the code") + null + } + } + + fun finallyBlock(): Int? { + return try { + val message = "Welcome to Kotlin Tutorials" + message.toInt() + } catch (exception: NumberFormatException) { + println("NumberFormatException in the code") + null + } finally { + println("In the Finally block") + } + } + + fun throwKeyword() { + val message = "Welcome to Kotlin Tutorials" + if (message.length > 10) throw IllegalArgumentException("String is invalid") + else println("String is valid") + } + + @Throws(IOException::class) + fun throwsAnnotation(): String?{ + val filePath = null + return filePath ?: throw IOException("File path is invalid") + } +} diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt new file mode 100644 index 0000000000..49ad3c38e0 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt @@ -0,0 +1,46 @@ +package com.baeldung.exceptionhandling + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import java.io.IOException +import kotlin.test.assertNull + +class ExceptionHandlingUnitTest { + + private val classUnderTest: ExceptionHandling = ExceptionHandling() + + @Test + fun givenInvalidConversion_whenTryCatchUsed_thenReturnsCatchBlockValue(){ + assertNull(classUnderTest.tryCatchBlock()) + } + + @Test + fun givenInvalidConversion_whenTryCatchExpressionUsed_thenReturnsCatchBlockValue(){ + assertNull(classUnderTest.tryCatchExpression()) + } + + @Test + fun givenDivisionByZero_whenMultipleCatchUsed_thenReturnsCatchBlockValue(){ + assertNull(classUnderTest.multipleCatchBlock()) + } + + @Test + fun givenDivisionByZero_whenNestedTryCatchUsed_thenReturnsNestedCatchBlockValue(){ + assertNull(classUnderTest.nestedTryCatchBlock()) + } + + @Test + fun givenInvalidConversion_whenTryCatchFinallyUsed_thenReturnsCatchAndFinallyBlock(){ + assertNull(classUnderTest.finallyBlock()) + } + + @Test + fun givenIllegalArgument_whenThrowKeywordUsed_thenThrowsException(){ + assertThrows { classUnderTest.throwKeyword() } + } + + @Test + fun whenAnnotationUsed_thenThrowsException(){ + assertThrows { classUnderTest.throwsAnnotation() } + } +} From 2c62d0214cc55b32625620bb7223699875138e75 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Wed, 15 Jul 2020 21:40:56 +0530 Subject: [PATCH 030/155] Add files via upload Difference between request.getSession() and request.getSession(true) --- .../WebContent/META-INF/MANIFEST.MF | 3 ++ .../WebContent/WEB-INF/web.xml | 34 +++++++++++++++++++ .../WebContent/index.html | 13 +++++++ .../src/httpsessionexample/FirstServlet.java | 33 ++++++++++++++++++ .../src/httpsessionexample/SecondServlet.java | 31 +++++++++++++++++ 5 files changed, 114 insertions(+) create mode 100644 spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF create mode 100644 spring-session/http-session-example/WebContent/WEB-INF/web.xml create mode 100644 spring-session/http-session-example/WebContent/index.html create mode 100644 spring-session/http-session-example/src/httpsessionexample/FirstServlet.java create mode 100644 spring-session/http-session-example/src/httpsessionexample/SecondServlet.java diff --git a/spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF b/spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..5e9495128c --- /dev/null +++ b/spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/spring-session/http-session-example/WebContent/WEB-INF/web.xml b/spring-session/http-session-example/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000000..6f88776c72 --- /dev/null +++ b/spring-session/http-session-example/WebContent/WEB-INF/web.xml @@ -0,0 +1,34 @@ + + + httpsessionexample + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + + +firstservlet +httpsessionexample.FirstServlet + + + +firstservlet +/firstservlet + + + +secondservlet +httpsessionexample.SecondServlet + + + +secondservlet +/secondservlet + + + + \ No newline at end of file diff --git a/spring-session/http-session-example/WebContent/index.html b/spring-session/http-session-example/WebContent/index.html new file mode 100644 index 0000000000..063d330854 --- /dev/null +++ b/spring-session/http-session-example/WebContent/index.html @@ -0,0 +1,13 @@ + + + + +Insert title here + + +
+Name:

+ +
+ + \ No newline at end of file diff --git a/spring-session/http-session-example/src/httpsessionexample/FirstServlet.java b/spring-session/http-session-example/src/httpsessionexample/FirstServlet.java new file mode 100644 index 0000000000..d49c0f3e14 --- /dev/null +++ b/spring-session/http-session-example/src/httpsessionexample/FirstServlet.java @@ -0,0 +1,33 @@ +package httpsessionexample; + +import java.io.PrintWriter; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class FirstServlet extends HttpServlet { + public void doGet(HttpServletRequest request, HttpServletResponse response) { + try { + HttpSession session = request.getSession(); + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + String name = request.getParameter("userName"); + out.print("Hi " + name); + + session.setAttribute("uname", name); + out.print("
"); + out.print("Session Id : " + session.getId()); + out.print("
"); + out.print("Second Servlet"); + + out.close(); + + } catch (Exception e) { + System.out.println(e); + } + } + +} diff --git a/spring-session/http-session-example/src/httpsessionexample/SecondServlet.java b/spring-session/http-session-example/src/httpsessionexample/SecondServlet.java new file mode 100644 index 0000000000..ab0b9c34ad --- /dev/null +++ b/spring-session/http-session-example/src/httpsessionexample/SecondServlet.java @@ -0,0 +1,31 @@ +package httpsessionexample; + +import java.io.PrintWriter; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class SecondServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) { + try { + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + HttpSession session = request.getSession(true); + String name = (String) session.getAttribute("uname"); + out.print("Hi " + name); + out.print("
"); + out.print("Session Id : " + session.getId()); + out.print("
"); + out.close(); + + } catch (Exception e) { + System.out.println(e); + } + } + +} From 26cc3e84d2cf5376fb30b9e9d06a5106fae7cafc Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Wed, 15 Jul 2020 21:48:11 +0530 Subject: [PATCH 031/155] Update README.md Difference Between request.getSession() and request.getSession(true) --- spring-session/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-session/README.md b/spring-session/README.md index 65040ec734..05343f67c2 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -6,3 +6,4 @@ This module contains articles about Spring Session - [Guide to Spring Session](https://www.baeldung.com/spring-session) - [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) - [Spring Session with MongoDB](https://www.baeldung.com/spring-session-mongodb) +- [Difference Between request.getSession() and request.getSession(true)](http://inprogress.baeldung.com/?p=215685&preview=true) From 8a76711fb522814c9f0e862f9692565b1885d0cc Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Thu, 16 Jul 2020 00:38:26 +0200 Subject: [PATCH 032/155] Minor code refinement --- .../com/baeldung/exceptionhandling/ExceptionHandling.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt index 137a303edb..225a1339e2 100644 --- a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt +++ b/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt @@ -28,7 +28,7 @@ class ExceptionHandling { fun multipleCatchBlock(): Int? { return try { val result = 25 / 0 - return result + result } catch (exception: NumberFormatException) { println("NumberFormatException in the code") null @@ -69,10 +69,10 @@ class ExceptionHandling { } } - fun throwKeyword() { + fun throwKeyword(): Int { val message = "Welcome to Kotlin Tutorials" if (message.length > 10) throw IllegalArgumentException("String is invalid") - else println("String is valid") + else return message.length } @Throws(IOException::class) From 3802825c6117bb4aa1a76f3ff31b3add9db5fc6b Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:57:33 +0530 Subject: [PATCH 033/155] Delete pom.xml --- bookstore/pom.xml | 23 ----------------------- 1 file changed, 23 deletions(-) delete mode 100644 bookstore/pom.xml diff --git a/bookstore/pom.xml b/bookstore/pom.xml deleted file mode 100644 index 68286076e5..0000000000 --- a/bookstore/pom.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 4.0.0 - com.hexagonal - bookstore - 0.0.1-SNAPSHOT - - - 1.8 - - - - org.springframework.boot - spring-boot-starter-parent - 2.3.1.RELEASE - - - - - org.springframework.boot - spring-boot-starter-web - - - \ No newline at end of file From d578a7585ef77aa6598d18a0902a9d539360cf4f Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:57:50 +0530 Subject: [PATCH 034/155] Delete MainApp.java --- bookstore/src/main/java/com/hexagonal/MainApp.java | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/MainApp.java diff --git a/bookstore/src/main/java/com/hexagonal/MainApp.java b/bookstore/src/main/java/com/hexagonal/MainApp.java deleted file mode 100644 index 0d6ef861b3..0000000000 --- a/bookstore/src/main/java/com/hexagonal/MainApp.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.hexagonal; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; - -@SpringBootApplication -public class MainApp { - public static void main(String[] args) { - SpringApplication.run(MainApp.class, args); - } - -} \ No newline at end of file From de2955f4b39edd9a2ef80ca0bcdb5aabcef1a172 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:58:07 +0530 Subject: [PATCH 035/155] Delete BookController.java --- .../hexagonal/controller/BookController.java | 37 ------------------- 1 file changed, 37 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/controller/BookController.java diff --git a/bookstore/src/main/java/com/hexagonal/controller/BookController.java b/bookstore/src/main/java/com/hexagonal/controller/BookController.java deleted file mode 100644 index 7e525deaa1..0000000000 --- a/bookstore/src/main/java/com/hexagonal/controller/BookController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.hexagonal.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.MediaType; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.hexagonal.domain.Book; -import com.hexagonal.service.BookService; - -@RestController -public class BookController { - - @Autowired - private BookService bookService; - - @RequestMapping("/book/add") - @PostMapping(produces = { MediaType.TEXT_PLAIN_VALUE }) - public void addBook(@RequestBody Book book) { - bookService.addBook(book); - } - - public Book buyBook(@PathVariable String isbn) { - return bookService.buyBook(isbn); - } - - public List listBooks() { - return bookService.listBooks(); - } - -} From d7a9fe81f9457a849cca901e4fba5d56c516213b Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:58:24 +0530 Subject: [PATCH 036/155] Delete Book.java --- .../main/java/com/hexagonal/domain/Book.java | 38 ------------------- 1 file changed, 38 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/domain/Book.java diff --git a/bookstore/src/main/java/com/hexagonal/domain/Book.java b/bookstore/src/main/java/com/hexagonal/domain/Book.java deleted file mode 100644 index 84125391cc..0000000000 --- a/bookstore/src/main/java/com/hexagonal/domain/Book.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.hexagonal.domain; - -public class Book { - - private String name; - private String isbn; - private String author; - - @Override - public String toString() { - return "Book [name=" + name + ", ISBN=" + isbn + ", author=" + author + "]"; - } - - public String getIsbn() { - return isbn; - } - - public void setIsbn(String isbn) { - this.isbn = isbn; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - -} From fc717bb9f173d3f5e82fcef9c5ddde8e6fe1971a Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:58:40 +0530 Subject: [PATCH 037/155] Delete BookRepository.java --- .../com/hexagonal/repository/BookRepository.java | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/repository/BookRepository.java diff --git a/bookstore/src/main/java/com/hexagonal/repository/BookRepository.java b/bookstore/src/main/java/com/hexagonal/repository/BookRepository.java deleted file mode 100644 index 1e64a2d21b..0000000000 --- a/bookstore/src/main/java/com/hexagonal/repository/BookRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.hexagonal.repository; - -import java.util.List; - -import com.hexagonal.domain.Book; - -public interface BookRepository { - - public void add(Book book); - - public Book buy(String isbn); - - public List list(); - -} From d600c40573a71db98d0c5a399201df0ec65f35b5 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:58:51 +0530 Subject: [PATCH 038/155] Delete BookRepositoryImpl.java --- .../repository/BookRepositoryImpl.java | 35 ------------------- 1 file changed, 35 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java diff --git a/bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java b/bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java deleted file mode 100644 index f4f99583dd..0000000000 --- a/bookstore/src/main/java/com/hexagonal/repository/BookRepositoryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.hexagonal.repository; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import org.springframework.stereotype.Repository; - -import com.hexagonal.domain.Book; - -@Repository -public class BookRepositoryImpl implements BookRepository { - - private Map bookMap = new HashMap<>(); - - @Override - public void add(Book book) { - bookMap.put(book.getIsbn(), book); - System.out.println("Book Added " + book); - } - - @Override - public Book buy(String isbn) { - return bookMap.get(isbn); - } - - @Override - public List list() { - return bookMap.values() - .stream() - .collect(Collectors.toList()); - } - -} From c7b9e81e15ad40ebc5fbfa803d3b2e0e5574de9c Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:59:07 +0530 Subject: [PATCH 039/155] Delete BookService.java --- .../java/com/hexagonal/service/BookService.java | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/service/BookService.java diff --git a/bookstore/src/main/java/com/hexagonal/service/BookService.java b/bookstore/src/main/java/com/hexagonal/service/BookService.java deleted file mode 100644 index cb5e1a930e..0000000000 --- a/bookstore/src/main/java/com/hexagonal/service/BookService.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.hexagonal.service; - -import java.util.List; - -import com.hexagonal.domain.Book; - -public interface BookService { - - public void addBook(Book book); - - public Book buyBook(String isbn); - - public List listBooks(); - -} From 8cdfb5b0efcd3789807a82d3ff793e341ff6081f Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 12:59:18 +0530 Subject: [PATCH 040/155] Delete BookServiceImpl.java --- .../hexagonal/service/BookServiceImpl.java | 35 ------------------- 1 file changed, 35 deletions(-) delete mode 100644 bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java diff --git a/bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java b/bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java deleted file mode 100644 index c7e660ea36..0000000000 --- a/bookstore/src/main/java/com/hexagonal/service/BookServiceImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.hexagonal.service; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.hexagonal.domain.Book; -import com.hexagonal.repository.BookRepository; - -@Service -public class BookServiceImpl implements BookService { - - @Autowired - private BookRepository bookRepository; - - @Override - public void addBook(Book book) { - bookRepository.add(book); - - } - - @Override - public Book buyBook(String isbn) { - - return bookRepository.buy(isbn); - } - - @Override - public List listBooks() { - - return bookRepository.list(); - } - -} From 52ff90ee1aebf36b2058d60e1b516f50993a7226 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 13:00:40 +0530 Subject: [PATCH 041/155] Update pom.xml --- spring-session/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 8388efb6c3..d5dbe28a2b 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -19,6 +19,7 @@ spring-session-jdbc spring-session-redis spring-session-mongodb + http-session-example -
\ No newline at end of file +
From 65b6b29ea1e52c666ef764449e1baa0b4d96022d Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 13:01:48 +0530 Subject: [PATCH 042/155] Update README.md --- spring-session/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-session/README.md b/spring-session/README.md index 05343f67c2..47125a6032 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -6,4 +6,4 @@ This module contains articles about Spring Session - [Guide to Spring Session](https://www.baeldung.com/spring-session) - [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) - [Spring Session with MongoDB](https://www.baeldung.com/spring-session-mongodb) -- [Difference Between request.getSession() and request.getSession(true)](http://inprogress.baeldung.com/?p=215685&preview=true) +- Difference Between request.getSession() and request.getSession(true) From 6d59756a7d0b2809640dc350fa334ce58986eda9 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 13:02:41 +0530 Subject: [PATCH 043/155] Update web.xml --- .../http-session-example/WebContent/WEB-INF/web.xml | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/spring-session/http-session-example/WebContent/WEB-INF/web.xml b/spring-session/http-session-example/WebContent/WEB-INF/web.xml index 6f88776c72..01b1b6f308 100644 --- a/spring-session/http-session-example/WebContent/WEB-INF/web.xml +++ b/spring-session/http-session-example/WebContent/WEB-INF/web.xml @@ -3,11 +3,6 @@ httpsessionexample index.html - index.htm - index.jsp - default.html - default.htm - default.jsp @@ -31,4 +26,4 @@ - \ No newline at end of file + From a8fc50e9b23c9bae382789f82bceea2208b9220c Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Fri, 17 Jul 2020 13:03:14 +0530 Subject: [PATCH 044/155] Delete MANIFEST.MF --- .../http-session-example/WebContent/META-INF/MANIFEST.MF | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF diff --git a/spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF b/spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF deleted file mode 100644 index 5e9495128c..0000000000 --- a/spring-session/http-session-example/WebContent/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Class-Path: - From 2923bae61f2704b707f0a8e7b266e0b2c7c99aad Mon Sep 17 00:00:00 2001 From: Krzysztof Woyke Date: Fri, 17 Jul 2020 13:12:36 +0200 Subject: [PATCH 045/155] JAVA-1634: Get rid of the overriden spring-boot.version property --- spring-cloud/spring-cloud-openfeign/pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/spring-cloud/spring-cloud-openfeign/pom.xml b/spring-cloud/spring-cloud-openfeign/pom.xml index df529d7fb1..c1f3f2dc30 100644 --- a/spring-cloud/spring-cloud-openfeign/pom.xml +++ b/spring-cloud/spring-cloud-openfeign/pom.xml @@ -51,8 +51,7 @@ - 2.0.1.RELEASE - Finchley.SR2 + Hoxton.SR6 From 8d6257111ab9d3ab11aee1a3ebc74e374628afc0 Mon Sep 17 00:00:00 2001 From: Anirban Chatterjee Date: Sat, 18 Jul 2020 12:54:29 +0200 Subject: [PATCH 046/155] Moved to new module --- .../com/baeldung/exceptionhandling/ExceptionHandling.kt | 5 +++++ .../baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt | 5 +++++ 2 files changed, 10 insertions(+) rename core-kotlin-modules/{core-kotlin-lang-2 => core-kotlin}/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt (93%) rename core-kotlin-modules/{core-kotlin-lang-2 => core-kotlin}/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt (88%) diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt similarity index 93% rename from core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt rename to core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt index 225a1339e2..6689ab43e4 100644 --- a/core-kotlin-modules/core-kotlin-lang-2/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt +++ b/core-kotlin-modules/core-kotlin/src/main/kotlin/com/baeldung/exceptionhandling/ExceptionHandling.kt @@ -75,6 +75,11 @@ class ExceptionHandling { else return message.length } + fun throwExpression(): Int? { + val message: String? = null + return message?.length ?: throw IllegalArgumentException("String is null") + } + @Throws(IOException::class) fun throwsAnnotation(): String?{ val filePath = null diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt similarity index 88% rename from core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt rename to core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt index 49ad3c38e0..af7aa4406f 100644 --- a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt +++ b/core-kotlin-modules/core-kotlin/src/test/kotlin/com/baeldung/exceptionhandling/ExceptionHandlingUnitTest.kt @@ -39,6 +39,11 @@ class ExceptionHandlingUnitTest { assertThrows { classUnderTest.throwKeyword() } } + @Test + fun givenIllegalArgument_whenElvisExpressionUsed_thenThrowsException(){ + assertThrows { classUnderTest.throwExpression() } + } + @Test fun whenAnnotationUsed_thenThrowsException(){ assertThrows { classUnderTest.throwsAnnotation() } From 2f2450fbb9c0d98a98e9c2142f089389bb540f89 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 18 Jul 2020 23:49:58 +0530 Subject: [PATCH 047/155] used standard parent in the project --- patterns/hexagonal-architecture/pom.xml | 13 +++++++------ ...plTest.java => EmployeeServiceImplUnitTest.java} | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) rename patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/{EmployeeServiceImplTest.java => EmployeeServiceImplUnitTest.java} (97%) diff --git a/patterns/hexagonal-architecture/pom.xml b/patterns/hexagonal-architecture/pom.xml index 9317a25e56..62f55c2efa 100644 --- a/patterns/hexagonal-architecture/pom.xml +++ b/patterns/hexagonal-architecture/pom.xml @@ -2,18 +2,19 @@ 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.3.0.RELEASE - - com.baeldung hexagonal-architecture 1.0 hexagonal-architecture Project for hexagonal architecture in java + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + 1.8 diff --git a/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java b/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplUnitTest.java similarity index 97% rename from patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java rename to patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplUnitTest.java index cadb3b094b..542e45d6f4 100644 --- a/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplTest.java +++ b/patterns/hexagonal-architecture/src/test/java/com/baeldung/pattern/hexagonal/domain/services/EmployeeServiceImplUnitTest.java @@ -11,7 +11,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -class EmployeeServiceImplTest { +class EmployeeServiceImplUnitTest { private EmployeeRepository employeeRepository; private EmployeeService testService; From 09ac6a9cf99be3ef849e87ca14a0d8eb79670213 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 19 Jul 2020 00:57:36 +0530 Subject: [PATCH 048/155] fix for the build warning --- spring-security-modules/spring-security-config/cors/pom.xml | 1 + spring-security-modules/spring-security-config/pom.xml | 1 + 2 files changed, 2 insertions(+) diff --git a/spring-security-modules/spring-security-config/cors/pom.xml b/spring-security-modules/spring-security-config/cors/pom.xml index 19ca7f5ccc..175b21a77d 100644 --- a/spring-security-modules/spring-security-config/cors/pom.xml +++ b/spring-security-modules/spring-security-config/cors/pom.xml @@ -11,6 +11,7 @@ com.baeldung spring-security-modules 0.0.1-SNAPSHOT + ../../ diff --git a/spring-security-modules/spring-security-config/pom.xml b/spring-security-modules/spring-security-config/pom.xml index b3796d1cc6..2b6b6b6b4e 100644 --- a/spring-security-modules/spring-security-config/pom.xml +++ b/spring-security-modules/spring-security-config/pom.xml @@ -11,6 +11,7 @@ com.baeldung parent-modules 1.0.0-SNAPSHOT + ../../ From 9b7caf3118b9b7b051fbed8f9f5b6a874996c876 Mon Sep 17 00:00:00 2001 From: STS Date: Sun, 19 Jul 2020 10:15:37 +0200 Subject: [PATCH 049/155] change excel file direcory --- .../{setFormula => setformula}/ExcelFormula.java | 2 +- .../poi/excel/setformula}/SetFormulaTest.xlsx | Bin .../ExcelFormulaUnitTest.java | 4 ++-- 3 files changed, 3 insertions(+), 3 deletions(-) rename apache-poi/src/main/java/com/baeldung/poi/excel/{setFormula => setformula}/ExcelFormula.java (93%) rename apache-poi/src/main/resources/{ => com/bealdung/poi/excel/setformula}/SetFormulaTest.xlsx (100%) rename apache-poi/src/test/java/com/baeldung/poi/excel/{setFormula => setformula}/ExcelFormulaUnitTest.java (93%) diff --git a/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java b/apache-poi/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java similarity index 93% rename from apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java rename to apache-poi/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java index 8b1ca5a89a..f5179b19c9 100644 --- a/apache-poi/src/main/java/com/baeldung/poi/excel/setFormula/ExcelFormula.java +++ b/apache-poi/src/main/java/com/baeldung/poi/excel/setformula/ExcelFormula.java @@ -1,4 +1,4 @@ -package com.baeldung.poi.excel.setFormula; +package com.baeldung.poi.excel.setformula; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator; diff --git a/apache-poi/src/main/resources/SetFormulaTest.xlsx b/apache-poi/src/main/resources/com/bealdung/poi/excel/setformula/SetFormulaTest.xlsx similarity index 100% rename from apache-poi/src/main/resources/SetFormulaTest.xlsx rename to apache-poi/src/main/resources/com/bealdung/poi/excel/setformula/SetFormulaTest.xlsx diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java similarity index 93% rename from apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java rename to apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java index 990b93fcbb..45314519d4 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/setFormula/ExcelFormulaUnitTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.poi.excel.setFormula; +package com.baeldung.poi.excel.setformula; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFSheet; @@ -14,7 +14,7 @@ import java.net.URISyntaxException; import java.nio.file.Paths; class ExcelFormulaUnitTest { - private static String FILE_NAME = "SetFormulaTest.xlsx"; + private static String FILE_NAME = "com/bealdung/poi/excel/setformula/SetFormulaTest.xlsx"; private String fileLocation; private ExcelFormula excelFormula; From 2a88d24386eec8969f275f25d3b226e3ac944313 Mon Sep 17 00:00:00 2001 From: developerDiv Date: Sat, 11 Jul 2020 16:42:03 +0100 Subject: [PATCH 050/155] Initial commit of ArgumentCaptor --- .../argumentcaptor/AuthenticationStatus.java | 7 ++ .../mockito/argumentcaptor/Credentials.java | 15 +++ .../argumentcaptor/DeliveryPlatform.java | 10 ++ .../mockito/argumentcaptor/Email.java | 47 ++++++++ .../mockito/argumentcaptor/EmailService.java | 36 +++++++ .../mockito/argumentcaptor/Format.java | 6 ++ .../mockito/argumentcaptor/ServiceStatus.java | 7 ++ .../argumentcaptor/EmailServiceUnitTest.java | 100 ++++++++++++++++++ 8 files changed, 228 insertions(+) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Email.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java new file mode 100644 index 0000000000..8307b4323b --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/AuthenticationStatus.java @@ -0,0 +1,7 @@ +package com.baeldung.mockito.argumentcaptor; + +public enum AuthenticationStatus { + AUTHENTICATED, + NOT_AUTHENTICATED, + ERROR +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java new file mode 100644 index 0000000000..5aec15505e --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java @@ -0,0 +1,15 @@ +package com.baeldung.mockito.argumentcaptor; + +public class Credentials { + private final String name; + private final String password; + private final String key; + + public Credentials(String name, String password, String key) { + + this.name = name; + this.password = password; + this.key = key; + } +} + diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java new file mode 100644 index 0000000000..dbad1e1bcf --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java @@ -0,0 +1,10 @@ +package com.baeldung.mockito.argumentcaptor; + +public interface DeliveryPlatform { + + void send(Email email); + + String getServiceStatus(); + + AuthenticationStatus authenticate(Credentials credentials); +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Email.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Email.java new file mode 100644 index 0000000000..6fc753a31c --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Email.java @@ -0,0 +1,47 @@ +package com.baeldung.mockito.argumentcaptor; + +public class Email { + + private String address; + private String subject; + private String body; + private Format format; + + public Email(String address, String subject, String body) { + this.address = address; + this.subject = subject; + this.body = body; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public Format getFormat() { + return format; + } + + public void setFormat(Format format) { + this.format = format; + } +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java new file mode 100644 index 0000000000..c368f41d2f --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java @@ -0,0 +1,36 @@ +package com.baeldung.mockito.argumentcaptor; + +public class EmailService { + + private DeliveryPlatform platform; + + public EmailService(DeliveryPlatform platform) { + this.platform = platform; + } + + public void send(String to, String subject, String body, boolean html) { + Format format = Format.TEXT_ONLY; + if (html) { + format = Format.HTML; + } + Email email = new Email(to, subject, body); + email.setFormat(format); + platform.send(email); + } + + public ServiceStatus checkServiceStatus() { + if (platform.getServiceStatus().equals("OK")) { + return ServiceStatus.UP; + } else { + return ServiceStatus.DOWN; + } + } + + public boolean authenticatedSuccessfully(Credentials credentials) { + if (platform.authenticate(credentials).equals(AuthenticationStatus.AUTHENTICATED)) { + return true; + } else { + return false; + } + } +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java new file mode 100644 index 0000000000..4c10375159 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Format.java @@ -0,0 +1,6 @@ +package com.baeldung.mockito.argumentcaptor; + +public enum Format { + TEXT_ONLY, + HTML +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java new file mode 100644 index 0000000000..65def5af64 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/ServiceStatus.java @@ -0,0 +1,7 @@ +package com.baeldung.mockito.argumentcaptor; + +public enum ServiceStatus { + UP, + DOWN, + AUTHENTICATED +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java new file mode 100644 index 0000000000..cdae118e92 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.mockito.argumentcaptor; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class EmailServiceUnitTest { + + @InjectMocks + EmailService emailService; + + @Mock + DeliveryPlatform platform; + + @Captor + ArgumentCaptor emailCaptor; + + @Captor + ArgumentCaptor credentialsCaptor; + + @Test + public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Article on using ArgumentCaptor"; + + emailService.send(to, subject, body, false); + + verify(platform).send(emailCaptor.capture()); + Email emailCaptorValue = emailCaptor.getValue(); + assertEquals(Format.TEXT_ONLY, emailCaptorValue.getFormat()); + } + + @Test + public void send_whenDoesSupportHtml_expectHTMLEmailFormat() { + String to = "baeldung@baeldung.com"; + String subject = "Great New Course!"; + String body = "Try out our new course."; + + emailService.send(to, subject, body, true); + + verify(platform).send(emailCaptor.capture()); + Email value = emailCaptor.getValue(); + assertEquals(Format.HTML, value.getFormat()); + } + + @Test + public void getServiceStatus_whenServiceRunning_expectUpResponse() { + when(platform.getServiceStatus()).thenReturn("OK"); + + ServiceStatus serviceStatus = emailService.checkServiceStatus(); + + assertEquals(ServiceStatus.UP, serviceStatus); + } + + @Test + public void getServiceStatus_whenServiceNotRunning_expectDownResponse() { + when(platform.getServiceStatus()).thenReturn("Error"); + + ServiceStatus serviceStatus = emailService.checkServiceStatus(); + + assertEquals(ServiceStatus.DOWN, serviceStatus); + } + + @Test + public void usingArgumemtMatcher_whenAuthenticatedWithValidCredentials_expectTrue() { + Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); + + assertTrue(emailService.authenticatedSuccessfully(credentials)); + } + + @Test + public void usingArgumentCapture_whenAuthenticatedWithValidCredentials_expectTrue() { + Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); + when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); + + assertTrue(emailService.authenticatedSuccessfully(credentials)); + assertEquals(credentials, credentialsCaptor.getValue()); + } + + @Test + public void authenticate_whenNotAuthenticated_expectFalse() { + Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); + when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); + + assertFalse(emailService.authenticatedSuccessfully(credentials)); + assertEquals(credentials, credentialsCaptor.getValue()); + } +} \ No newline at end of file From 92b1c62c1aebdbef3699e3a97ff9ee888550b212 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:29:41 +0530 Subject: [PATCH 051/155] JAVA-66: New module spring-data-jpa-annotations --- .../spring-data-jpa-annotations/README.md | 23 +++ .../spring-data-jpa-annotations/pom.xml | 77 +++++++++ .../main/java/com/baeldung/Application.java | 13 ++ .../baeldung/boot/ddd/event/Aggregate.java | 46 ++++++ .../baeldung/boot/ddd/event/Aggregate2.java | 44 +++++ .../boot/ddd/event/Aggregate2Repository.java | 10 ++ .../baeldung/boot/ddd/event/Aggregate3.java | 23 +++ .../boot/ddd/event/Aggregate3Repository.java | 14 ++ .../boot/ddd/event/AggregateRepository.java | 10 ++ .../baeldung/boot/ddd/event/DddConfig.java | 15 ++ .../baeldung/boot/ddd/event/DomainEvent.java | 8 + .../boot/ddd/event/DomainService.java | 31 ++++ .../baeldung/composite/BookApplication.java | 12 ++ .../com/baeldung/composite/entity/Book.java | 47 ++++++ .../com/baeldung/composite/entity/BookId.java | 51 ++++++ .../composite/repository/BookRepository.java | 18 +++ .../baeldung/embeddable/model/Company.java | 71 ++++++++ .../embeddable/model/ContactPerson.java | 38 +++++ .../repositories/CompanyRepository.java | 18 +++ .../SpringBootLifecycleEventApplication.java | 11 ++ .../model/AuditTrailListener.java | 39 +++++ .../baeldung/lifecycleevents/model/User.java | 104 ++++++++++++ .../repository/UserRepository.java | 9 ++ .../java/com/baeldung/tx/TxApplication.java | 13 ++ .../java/com/baeldung/tx/model/Payment.java | 55 +++++++ .../src/main/resources/application.properties | 6 + .../src/main/resources/ddd.properties | 1 + .../src/main/resources/logback.xml | 13 ++ .../src/main/resources/persistence.properties | 14 ++ .../Aggregate2EventsIntegrationTest.java | 72 +++++++++ .../Aggregate3EventsIntegrationTest.java | 67 ++++++++ .../event/AggregateEventsIntegrationTest.java | 87 ++++++++++ .../boot/ddd/event/TestEventHandler.java | 14 ++ .../BookRepositoryIntegrationTest.java | 64 ++++++++ .../embeddable/EmbeddableIntegrationTest.java | 125 ++++++++++++++ .../tx/ManualTransactionIntegrationTest.java | 152 ++++++++++++++++++ .../UserRepositoryIntegrationTest.java | 80 +++++++++ 37 files changed, 1495 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-annotations/README.md create mode 100644 persistence-modules/spring-data-jpa-annotations/pom.xml create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainService.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/BookApplication.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/Book.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/BookId.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/repository/BookRepository.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/Company.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/ContactPerson.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/User.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/TxApplication.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/model/Payment.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/resources/ddd.properties create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/resources/logback.xml create mode 100644 persistence-modules/spring-data-jpa-annotations/src/main/resources/persistence.properties create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-annotations/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa-annotations/README.md b/persistence-modules/spring-data-jpa-annotations/README.md new file mode 100644 index 0000000000..5f1c8dbc27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/README.md @@ -0,0 +1,23 @@ +## Spring Data JPA - Annotations + +This module contains articles about annotations used in Spring Data JPA + +### Relevant articles + +- [Spring Data Annotations](https://www.baeldung.com/spring-data-annotations) +- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) +- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) +- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) +- [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) +- [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) +- [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/persistence-modules/spring-data-jpa-annotations/pom.xml b/persistence-modules/spring-data-jpa-annotations/pom.xml new file mode 100644 index 0000000000..67b788c404 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + spring-data-jpa-annotations + spring-data-jpa-annotations + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hibernate + hibernate-ehcache + + + org.hibernate + hibernate-envers + + + + com.h2database + h2 + + + + + org.testcontainers + postgresql + ${testcontainers.postgresql.version} + test + + + + org.postgresql + postgresql + + + + + org.springframework.security + spring-security-test + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.google.guava + guava + ${guava.version} + + + + + com.baeldung.boot.Application + 1.10.6 + 42.2.5 + 21.0 + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..3ea3d113da --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java new file mode 100644 index 0000000000..e435f4c85c --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java @@ -0,0 +1,46 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Transient; + +import org.springframework.context.ApplicationEventPublisher; + +@Entity +class Aggregate { + @Transient + private ApplicationEventPublisher eventPublisher; + @Id + private long id; + + private Aggregate() { + } + + Aggregate(long id, ApplicationEventPublisher eventPublisher) { + this.id = id; + this.eventPublisher = eventPublisher; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "DomainEntity [id=" + id + "]"; + } + + void domainOperation() { + // some business logic + if (eventPublisher != null) { + eventPublisher.publishEvent(new DomainEvent()); + } + } + + long getId() { + return id; + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java new file mode 100644 index 0000000000..08f61db812 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java @@ -0,0 +1,44 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Transient; + +import org.springframework.data.domain.AfterDomainEventPublication; +import org.springframework.data.domain.DomainEvents; + +@Entity +public class Aggregate2 { + @Transient + private final Collection domainEvents; + @Id + @GeneratedValue + private long id; + + public Aggregate2() { + domainEvents = new ArrayList<>(); + } + + @AfterDomainEventPublication + public void clearEvents() { + domainEvents.clear(); + } + + public void domainOperation() { + // some domain operation + domainEvents.add(new DomainEvent()); + } + + @DomainEvents + public Collection events() { + return domainEvents; + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java new file mode 100644 index 0000000000..7f09c410fc --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java @@ -0,0 +1,10 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +public interface Aggregate2Repository extends CrudRepository { + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java new file mode 100644 index 0000000000..f664322a59 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java @@ -0,0 +1,23 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +import org.springframework.data.domain.AbstractAggregateRoot; + +@Entity +public class Aggregate3 extends AbstractAggregateRoot { + @Id + @GeneratedValue + private long id; + + public void domainOperation() { + // some domain operation + registerEvent(new DomainEvent()); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java new file mode 100644 index 0000000000..93f50bb5cf --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java @@ -0,0 +1,14 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +/** + * @author goobar + * + */ +public interface Aggregate3Repository extends CrudRepository { + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java new file mode 100644 index 0000000000..1c2d3884bf --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java @@ -0,0 +1,10 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import org.springframework.data.repository.CrudRepository; + +public interface AggregateRepository extends CrudRepository { + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java new file mode 100644 index 0000000000..34cf21463b --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java @@ -0,0 +1,15 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.annotation.PropertySource; + +@SpringBootConfiguration +@EnableAutoConfiguration +@PropertySource("classpath:/ddd.properties") +public class DddConfig { + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java new file mode 100644 index 0000000000..e7626e742d --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java @@ -0,0 +1,8 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +class DomainEvent { + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainService.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainService.java new file mode 100644 index 0000000000..80aa5ca6cb --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/boot/ddd/event/DomainService.java @@ -0,0 +1,31 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import javax.transaction.Transactional; + +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; + +@Service +public class DomainService { + private final ApplicationEventPublisher eventPublisher; + private final AggregateRepository repository; + + public DomainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { + this.repository = repository; + this.eventPublisher = eventPublisher; + } + + @Transactional + public void serviceDomainOperation(long entityId) { + repository.findById(entityId) + .ifPresent(entity -> { + entity.domainOperation(); + repository.save(entity); + eventPublisher.publishEvent(new DomainEvent()); + }); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/BookApplication.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/BookApplication.java new file mode 100644 index 0000000000..52f06058aa --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/BookApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.composite; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BookApplication { + + public static void main(String[] args) { + SpringApplication.run(BookApplication.class); + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/Book.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/Book.java new file mode 100644 index 0000000000..e4f1727654 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/Book.java @@ -0,0 +1,47 @@ +package com.baeldung.composite.entity; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class Book { + + @EmbeddedId + private BookId id; + private String genre; + private Integer price; + + public Book() { + } + + public Book(String author, String name, String genre, Integer price) { + BookId id = new BookId(author, name); + this.id = id; + this.genre = genre; + this.price = price; + } + + public BookId getId() { + return id; + } + + public void setId(BookId id) { + this.id = id; + } + + public String getGenre() { + return genre; + } + + public void setGenre(String genre) { + this.genre = genre; + } + + public Integer getPrice() { + return price; + } + + public void setPrice(Integer price) { + this.price = price; + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/BookId.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/BookId.java new file mode 100644 index 0000000000..1524452412 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/entity/BookId.java @@ -0,0 +1,51 @@ +package com.baeldung.composite.entity; + +import javax.persistence.Embeddable; +import java.io.Serializable; +import java.util.Objects; + +@Embeddable +public class BookId implements Serializable { + + private String author; + private String name; + + public BookId() { + } + + public BookId(String author, String name) { + this.author = author; + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + BookId bookId = (BookId) o; + return Objects.equals(author, bookId.author) && Objects.equals(name, bookId.name); + } + + @Override + public int hashCode() { + return Objects.hash(author, name); + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/repository/BookRepository.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/repository/BookRepository.java new file mode 100644 index 0000000000..d5993eaf79 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/composite/repository/BookRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.composite.repository; + +import com.baeldung.composite.entity.Book; +import com.baeldung.composite.entity.BookId; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface BookRepository extends JpaRepository { + + List findByIdName(String name); + + List findByIdAuthor(String author); + + List findByGenre(String genre); +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/Company.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/Company.java new file mode 100644 index 0000000000..203cff1e35 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/Company.java @@ -0,0 +1,71 @@ +package com.baeldung.embeddable.model; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Company { + + @Id + @GeneratedValue + private Integer id; + + private String name; + + private String address; + + private String phone; + + @Embedded + @AttributeOverrides(value = { + @AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")), + @AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name")), + @AttributeOverride( name = "phone", column = @Column(name = "contact_phone")) + }) + private ContactPerson contactPerson; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public ContactPerson getContactPerson() { + return contactPerson; + } + + public void setContactPerson(ContactPerson contactPerson) { + this.contactPerson = contactPerson; + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/ContactPerson.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/ContactPerson.java new file mode 100644 index 0000000000..561da80878 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/model/ContactPerson.java @@ -0,0 +1,38 @@ +package com.baeldung.embeddable.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class ContactPerson { + + private String firstName; + + private String lastName; + + private String phone; + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java new file mode 100644 index 0000000000..f456b15652 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.embeddable.repositories; + +import com.baeldung.embeddable.model.Company; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface CompanyRepository extends JpaRepository { + + List findByContactPersonFirstName(String firstName); + + @Query("SELECT C FROM Company C WHERE C.contactPerson.firstName = ?1") + List findByContactPersonFirstNameWithJPQL(String firstName); + + @Query(value = "SELECT * FROM company WHERE contact_first_name = ?1", nativeQuery = true) + List findByContactPersonFirstNameWithNativeQuery(String firstName); +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java new file mode 100644 index 0000000000..fbc861c5fe --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.lifecycleevents; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootLifecycleEventApplication { + public static void main(String[] args) { + SpringApplication.run(SpringBootLifecycleEventApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java new file mode 100644 index 0000000000..26ebff42e4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java @@ -0,0 +1,39 @@ +package com.baeldung.lifecycleevents.model; + +import javax.persistence.PostLoad; +import javax.persistence.PostPersist; +import javax.persistence.PostRemove; +import javax.persistence.PostUpdate; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class AuditTrailListener { + private static Log log = LogFactory.getLog(AuditTrailListener.class); + + @PrePersist + @PreUpdate + @PreRemove + private void beforeAnyUpdate(User user) { + if (user.getId() == 0) { + log.info("[USER AUDIT] About to add a user"); + } else { + log.info("[USER AUDIT] About to update/delete user: " + user.getId()); + } + } + + @PostPersist + @PostUpdate + @PostRemove + private void afterAnyUpdate(User user) { + log.info("[USER AUDIT] add/update/delete complete for user: " + user.getId()); + } + + @PostLoad + private void afterLoad(User user) { + log.info("[USER AUDIT] user loaded from database: " + user.getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/User.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/User.java new file mode 100644 index 0000000000..a080cb3bf2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/model/User.java @@ -0,0 +1,104 @@ +package com.baeldung.lifecycleevents.model; + +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.PostLoad; +import javax.persistence.PostPersist; +import javax.persistence.PostRemove; +import javax.persistence.PostUpdate; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; +import javax.persistence.Transient; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +@Entity +@EntityListeners(AuditTrailListener.class) +public class User { + private static Log log = LogFactory.getLog(User.class); + + @Id + @GeneratedValue + private int id; + + private String userName; + private String firstName; + private String lastName; + @Transient + private String fullName; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getFullName() { + return fullName; + } + + @PrePersist + public void logNewUserAttempt() { + log.info("Attempting to add new user with username: " + userName); + } + + @PostPersist + public void logNewUserAdded() { + log.info("Added user '" + userName + "' with ID: " + id); + } + + @PreRemove + public void logUserRemovalAttempt() { + log.info("Attempting to delete user: " + userName); + } + + @PostRemove + public void logUserRemoval() { + log.info("Deleted user: " + userName); + } + + @PreUpdate + public void logUserUpdateAttempt() { + log.info("Attempting to update user: " + userName); + } + + @PostUpdate + public void logUserUpdate() { + log.info("Updated user: " + userName); + } + + @PostLoad + public void logUserLoad() { + fullName = firstName + " " + lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java new file mode 100644 index 0000000000..af14117ebb --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.lifecycleevents.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.lifecycleevents.model.User; + +public interface UserRepository extends JpaRepository { + public User findByUserName(String userName); +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/TxApplication.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/TxApplication.java new file mode 100644 index 0000000000..4c982c91e9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/TxApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.tx; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TxApplication { + + public static void main(String[] args) { + SpringApplication.run(TxApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/model/Payment.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/model/Payment.java new file mode 100644 index 0000000000..921a1e9275 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/tx/model/Payment.java @@ -0,0 +1,55 @@ +package com.baeldung.tx.model; + +import javax.persistence.*; + +@Entity +public class Payment { + + @Id + @GeneratedValue + private Long id; + + private Long amount; + + @Column(unique = true) + private String referenceNumber; + + @Enumerated(EnumType.STRING) + private State state; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getAmount() { + return amount; + } + + public void setAmount(Long amount) { + this.amount = amount; + } + + public String getReferenceNumber() { + return referenceNumber; + } + + public void setReferenceNumber(String referenceNumber) { + this.referenceNumber = referenceNumber; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public enum State { + STARTED, FAILED, SUCCESSFUL + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-annotations/src/main/resources/application.properties new file mode 100644 index 0000000000..f127dd5e50 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.main.allow-bean-definition-overriding=true + +spring.jpa.properties.hibernate.jdbc.batch_size=4 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.generate_statistics=true diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/resources/ddd.properties b/persistence-modules/spring-data-jpa-annotations/src/main/resources/ddd.properties new file mode 100644 index 0000000000..e5126b694b --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/resources/ddd.properties @@ -0,0 +1 @@ +spring.datasource.initialization-mode=never \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa-annotations/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-annotations/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-annotations/src/main/resources/persistence.properties new file mode 100644 index 0000000000..6bc83edf34 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/main/resources/persistence.properties @@ -0,0 +1,14 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=true +hibernate.cache.use_query_cache=true +hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory + diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java new file mode 100644 index 0000000000..e76b932cb9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java @@ -0,0 +1,72 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import com.baeldung.boot.ddd.event.Aggregate2; +import com.baeldung.boot.ddd.event.Aggregate2Repository; +import com.baeldung.boot.ddd.event.DomainEvent; + +@SpringJUnitConfig +@SpringBootTest +class Aggregate2EventsIntegrationTest { + @MockBean + private TestEventHandler eventHandler; + @Autowired + private Aggregate2Repository repository; + + // @formatter:off + @DisplayName("given aggregate with @AfterDomainEventPublication," + + " when do domain operation and save twice," + + " then an event is published only for the first time") + // @formatter:on + @Test + void afterDomainEvents() { + // given + Aggregate2 aggregate = new Aggregate2(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + @BeforeEach + void beforeEach() { + repository.deleteAll(); + } + + // @formatter:off + @DisplayName("given aggregate with @DomainEvents," + + " when do domain operation and save," + + " then an event is published") + // @formatter:on + @Test + void domainEvents() { + // given + Aggregate2 aggregate = new Aggregate2(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java new file mode 100644 index 0000000000..4193e932ee --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java @@ -0,0 +1,67 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import com.baeldung.boot.ddd.event.Aggregate3; +import com.baeldung.boot.ddd.event.Aggregate3Repository; +import com.baeldung.boot.ddd.event.DomainEvent; + +@SpringJUnitConfig +@SpringBootTest +class Aggregate3EventsIntegrationTest { + + @MockBean + private TestEventHandler eventHandler; + @Autowired + private Aggregate3Repository repository; + + // @formatter:off + @DisplayName("given aggregate extending AbstractAggregateRoot," + + " when do domain operation and save twice," + + " then an event is published only for the first time") + // @formatter:on + @Test + void afterDomainEvents() { + // given + Aggregate3 aggregate = new Aggregate3(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + // @formatter:off + @DisplayName("given aggregate extending AbstractAggregateRoot," + + " when do domain operation and save," + + " then an event is published") + // @formatter:on + @Test + void domainEvents() { + // given + Aggregate3 aggregate = new Aggregate3(); + + // when + aggregate.domainOperation(); + repository.save(aggregate); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java new file mode 100644 index 0000000000..ac607063b2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.boot.ddd.event; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; + +import com.baeldung.boot.ddd.event.Aggregate; +import com.baeldung.boot.ddd.event.AggregateRepository; +import com.baeldung.boot.ddd.event.DomainEvent; +import com.baeldung.boot.ddd.event.DomainService; + +@SpringJUnitConfig +@SpringBootTest +class AggregateEventsIntegrationTest { + + @Autowired + private DomainService domainService; + + @MockBean + private TestEventHandler eventHandler; + @Autowired + private ApplicationEventPublisher eventPublisher; + @Autowired + private AggregateRepository repository; + + // @formatter:off + @DisplayName("given existing aggregate," + + " when do domain operation directly on aggregate," + + " then domain event is NOT published") + // @formatter:on + @Test + void aggregateEventsTest() { + Aggregate existingDomainEntity = new Aggregate(0, eventPublisher); + repository.save(existingDomainEntity); + + // when + repository.findById(existingDomainEntity.getId()) + .get() + .domainOperation(); + + // then + verifyZeroInteractions(eventHandler); + } + + @BeforeEach + void beforeEach() { + repository.deleteAll(); + } + + // @formatter:off + @DisplayName("given existing aggregate," + + " when do domain operation on service," + + " then domain event is published") + // @formatter:on + @Test + void serviceEventsTest() { + Aggregate existingDomainEntity = new Aggregate(1, eventPublisher); + repository.save(existingDomainEntity); + + // when + domainService.serviceDomainOperation(existingDomainEntity.getId()); + + // then + verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); + } + + @TestConfiguration + public static class TestConfig { + @Bean + public DomainService domainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { + return new DomainService(repository, eventPublisher); + } + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java new file mode 100644 index 0000000000..0f499834eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java @@ -0,0 +1,14 @@ +/** + * + */ +package com.baeldung.boot.ddd.event; + +import org.springframework.transaction.event.TransactionalEventListener; + +import com.baeldung.boot.ddd.event.DomainEvent; + +interface TestEventHandler { + @TransactionalEventListener + void handleEvent(DomainEvent event); + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9d25acbd96 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.composite.repository; + +import com.baeldung.composite.BookApplication; +import com.baeldung.composite.entity.Book; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +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.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = BookApplication.class) +public class BookRepositoryIntegrationTest { + + public static final String JAVA_101 = "Java101"; + public static final String JANE = "Jane"; + public static final String TECH = "Tech"; + @Autowired + BookRepository repository; + + @Before + public void setUp() { + Book book1 = new Book("John", JAVA_101, TECH, 20); + Book book2 = new Book(JANE, JAVA_101, "Arch", 25); + Book book3 = new Book(JANE, "Scala101", TECH, 23); + + repository.saveAll(Arrays.asList(book1, book2, book3)); + } + + @After + public void tearDown() { + repository.deleteAll(); + } + + @Test + public void testFindByName() { + List books = repository.findByIdName(JAVA_101); + + assertEquals(2, books.size()); + } + + @Test + public void testFindByAuthor() { + List books = repository.findByIdAuthor(JANE); + + assertEquals(2, books.size()); + } + + @Test + public void testFindByGenre() { + List books = repository.findByGenre(TECH); + + assertEquals(2, books.size()); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java new file mode 100644 index 0000000000..b4c365a2d9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.embeddable; + +import com.baeldung.Application; +import com.baeldung.embeddable.model.Company; +import com.baeldung.embeddable.model.ContactPerson; +import com.baeldung.embeddable.repositories.CompanyRepository; +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 org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {Application.class}) +public class EmbeddableIntegrationTest { + + @Autowired + private CompanyRepository companyRepository; + + @Test + @Transactional + public void whenInsertingCompany_thenEmbeddedContactPersonDetailsAreMapped() { + ContactPerson contactPerson = new ContactPerson(); + contactPerson.setFirstName("First"); + contactPerson.setLastName("Last"); + contactPerson.setPhone("123-456-789"); + + Company company = new Company(); + company.setName("Company"); + company.setAddress("1st street"); + company.setPhone("987-654-321"); + company.setContactPerson(contactPerson); + + companyRepository.save(company); + + Company result = companyRepository.getOne(company.getId()); + + assertEquals("Company", result.getName()); + assertEquals("1st street", result.getAddress()); + assertEquals("987-654-321", result.getPhone()); + assertEquals("First", result.getContactPerson().getFirstName()); + assertEquals("Last", result.getContactPerson().getLastName()); + assertEquals("123-456-789", result.getContactPerson().getPhone()); + } + + @Test + @Transactional + public void whenFindingCompanyByContactPersonAttribute_thenCompanyIsReturnedProperly() { + ContactPerson contactPerson = new ContactPerson(); + contactPerson.setFirstName("Name"); + contactPerson.setLastName("Last"); + contactPerson.setPhone("123-456-789"); + + Company company = new Company(); + company.setName("Company"); + company.setAddress("1st street"); + company.setPhone("987-654-321"); + company.setContactPerson(contactPerson); + + companyRepository.save(company); + + List result = companyRepository.findByContactPersonFirstName("Name"); + + assertEquals(1, result.size()); + + result = companyRepository.findByContactPersonFirstName("FirstName"); + + assertEquals(0, result.size()); + } + + @Test + @Transactional + public void whenFindingCompanyByContactPersonAttributeWithJPQL_thenCompanyIsReturnedProperly() { + ContactPerson contactPerson = new ContactPerson(); + contactPerson.setFirstName("@QueryName"); + contactPerson.setLastName("Last"); + contactPerson.setPhone("123-456-789"); + + Company company = new Company(); + company.setName("Company"); + company.setAddress("1st street"); + company.setPhone("987-654-321"); + company.setContactPerson(contactPerson); + + companyRepository.save(company); + + List result = companyRepository.findByContactPersonFirstNameWithJPQL("@QueryName"); + + assertEquals(1, result.size()); + + result = companyRepository.findByContactPersonFirstNameWithJPQL("FirstName"); + + assertEquals(0, result.size()); + } + + @Test + @Transactional + public void whenFindingCompanyByContactPersonAttributeWithNativeQuery_thenCompanyIsReturnedProperly() { + ContactPerson contactPerson = new ContactPerson(); + contactPerson.setFirstName("NativeQueryName"); + contactPerson.setLastName("Last"); + contactPerson.setPhone("123-456-789"); + + Company company = new Company(); + company.setName("Company"); + company.setAddress("1st street"); + company.setPhone("987-654-321"); + company.setContactPerson(contactPerson); + + companyRepository.save(company); + + List result = companyRepository.findByContactPersonFirstNameWithNativeQuery("NativeQueryName"); + + assertEquals(1, result.size()); + + result = companyRepository.findByContactPersonFirstNameWithNativeQuery("FirstName"); + + assertEquals(0, result.size()); + } +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java new file mode 100644 index 0000000000..01551348c9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java @@ -0,0 +1,152 @@ +package com.baeldung.tx; + +import com.baeldung.tx.model.Payment; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.TransactionCallbackWithoutResult; +import org.springframework.transaction.support.TransactionTemplate; + +import javax.persistence.EntityManager; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; + +@DataJpaTest +@ActiveProfiles("test") +@Transactional(propagation = NOT_SUPPORTED) +class ManualTransactionIntegrationTest { + + @Autowired + private PlatformTransactionManager transactionManager; + + @Autowired + private EntityManager entityManager; + + private TransactionTemplate transactionTemplate; + + @BeforeEach + void setUp() { + transactionTemplate = new TransactionTemplate(transactionManager); + } + + @AfterEach + void flushDb() { + transactionTemplate.execute(status -> entityManager + .createQuery("delete from Payment") + .executeUpdate()); + } + + @Test + void givenAPayment_WhenNotDuplicate_ThenShouldCommit() { + Long id = transactionTemplate.execute(status -> { + Payment payment = new Payment(); + payment.setAmount(1000L); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + + return payment.getId(); + }); + + Payment payment = entityManager.find(Payment.class, id); + assertThat(payment).isNotNull(); + } + + @Test + void givenAPayment_WhenMarkAsRollback_ThenShouldRollback() { + transactionTemplate.execute(status -> { + Payment payment = new Payment(); + payment.setAmount(1000L); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + status.setRollbackOnly(); + + return payment.getId(); + }); + + assertThat(entityManager + .createQuery("select p from Payment p", Payment.class) + .getResultList()).isEmpty(); + } + + @Test + void givenTwoPayments_WhenRefIsDuplicate_ThenShouldRollback() { + try { + transactionTemplate.execute(s -> { + Payment first = new Payment(); + first.setAmount(1000L); + first.setReferenceNumber("Ref-1"); + first.setState(Payment.State.SUCCESSFUL); + + Payment second = new Payment(); + second.setAmount(2000L); + second.setReferenceNumber("Ref-1"); + second.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(first); + entityManager.persist(second); + + return "Ref-1"; + }); + } catch (Exception ignored) { + } + + assertThat(entityManager + .createQuery("select p from Payment p", Payment.class) + .getResultList()).isEmpty(); + } + + @Test + void givenAPayment_WhenNotExpectingAnyResult_ThenShouldCommit() { + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + Payment payment = new Payment(); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + } + }); + + assertThat(entityManager + .createQuery("select p from Payment p", Payment.class) + .getResultList()).hasSize(1); + } + + @Test + void givenAPayment_WhenUsingTxManager_ThenShouldCommit() { + DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); + definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + definition.setTimeout(3); + + TransactionStatus status = transactionManager.getTransaction(definition); + try { + Payment payment = new Payment(); + payment.setReferenceNumber("Ref-1"); + payment.setState(Payment.State.SUCCESSFUL); + + entityManager.persist(payment); + transactionManager.commit(status); + } catch (Exception ex) { + transactionManager.rollback(status); + } + + assertThat(entityManager + .createQuery("select p from Payment p", Payment.class) + .getResultList()).hasSize(1); + } + +} diff --git a/persistence-modules/spring-data-jpa-annotations/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..078f437474 --- /dev/null +++ b/persistence-modules/spring-data-jpa-annotations/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java @@ -0,0 +1,80 @@ +package lifecycleevents; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.After; +import org.junit.Before; +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 com.baeldung.lifecycleevents.SpringBootLifecycleEventApplication; +import com.baeldung.lifecycleevents.model.User; +import com.baeldung.lifecycleevents.repository.UserRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = SpringBootLifecycleEventApplication.class) +public class UserRepositoryIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Before + public void setup() { + User user = new User(); + user.setFirstName("Jane"); + user.setLastName("Smith"); + user.setUserName("jsmith123"); + userRepository.save(user); + } + + @After + public void cleanup() { + userRepository.deleteAll(); + } + + @Test + public void whenNewUserProvided_userIsAdded() { + User user = new User(); + user.setFirstName("John"); + user.setLastName("Doe"); + user.setUserName("jdoe123"); + user = userRepository.save(user); + assertTrue(user.getId() > 0); + } + + @Test + public void whenUserNameProvided_userIsLoaded() { + User user = userRepository.findByUserName("jsmith123"); + assertNotNull(user); + assertEquals("jsmith123", user.getUserName()); + } + + @Test + public void whenExistingUserProvided_userIsUpdated() { + User user = userRepository.findByUserName("jsmith123"); + user.setFirstName("Joe"); + user = userRepository.save(user); + assertEquals("Joe", user.getFirstName()); + } + + @Test + public void whenExistingUserDeleted_userIsDeleted() { + User user = userRepository.findByUserName("jsmith123"); + userRepository.delete(user); + user = userRepository.findByUserName("jsmith123"); + assertNull(user); + } + + @Test + public void whenExistingUserLoaded_fullNameIsAvailable() { + String expectedFullName = "Jane Smith"; + User user = userRepository.findByUserName("jsmith123"); + assertEquals(expectedFullName, user.getFullName()); + } +} From 2ca8ec847cc3f31e3fcba06f82e5ade64187cdb6 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:30:00 +0530 Subject: [PATCH 052/155] JAVA-66: New module spring-data-jpa-crud --- .../spring-data-jpa-crud/README.md | 21 ++++ .../spring-data-jpa-crud/pom.xml | 71 ++++++++++++++ .../main/java/com/baeldung/Application.java | 14 +++ .../DatasourceProxyBeanPostProcessor.java | 53 ++++++++++ .../baeldung/batchinserts/model/School.java | 45 +++++++++ .../baeldung/batchinserts/model/Student.java | 44 +++++++++ .../java/com/baeldung/boot/Application.java | 17 ++++ .../boot/daos/CustomerRepository.java | 19 ++++ .../daos/impl/PersonInsertRepository.java | 31 ++++++ .../com/baeldung/boot/domain/Customer.java | 56 +++++++++++ .../java/com/baeldung/boot/domain/Person.java | 47 +++++++++ .../web/controllers/CustomerController.java | 41 ++++++++ .../baeldung/datajpadelete/entity/Book.java | 51 ++++++++++ .../datajpadelete/entity/Category.java | 60 ++++++++++++ .../repository/BookRepository.java | 19 ++++ .../repository/CategoryRepository.java | 9 ++ .../java/com/baeldung/entity/Employee.java | 36 +++++++ .../main/java/com/baeldung/entity/Fruit.java | 40 ++++++++ .../repository/EmployeeRepository.java | 9 ++ .../baeldung/repository/FruitRepository.java | 27 +++++ .../schemageneration/AccountApplication.java | 12 +++ .../schemageneration/HibernateUtil.java | 39 ++++++++ .../schemageneration/model/Account.java | 74 ++++++++++++++ .../model/AccountSetting.java | 68 +++++++++++++ .../repository/AccountRepository.java | 8 ++ .../repository/AccountSettingRepository.java | 8 ++ .../src/main/resources/application.properties | 14 +++ .../src/main/resources/logback.xml | 13 +++ .../java/com/baeldung/SpringContextTest.java | 17 ++++ .../SpringJpaContextIntegrationTest.java | 19 ++++ .../BatchInsertIntegrationTest.java | 40 ++++++++ .../JpaBatchInsertsIntegrationTest.java | 98 +++++++++++++++++++ .../JpaNoBatchInsertsIntegrationTest.java | 41 ++++++++ .../batchinserts/TestObjectHelper.java | 20 ++++ ...PersonInsertRepositoryIntegrationTest.java | 82 ++++++++++++++++ .../DeleteFromRepositoryUnitTest.java | 72 ++++++++++++++ .../DeleteInRelationshipsUnitTest.java | 60 ++++++++++++ .../EmployeeRepositoryIntegrationTest.java | 40 ++++++++ .../FruitRepositoryIntegrationTest.java | 75 ++++++++++++++ .../AccountRepositoryIntegrationTest.java | 72 ++++++++++++++ .../application-batchinserts.properties | 6 ++ .../resources/application-test.properties | 2 + .../src/test/resources/test-fruit-data.sql | 6 ++ 43 files changed, 1596 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-crud/README.md create mode 100644 persistence-modules/spring-data-jpa-crud/pom.xml create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/School.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/Student.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/Application.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/CustomerRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Customer.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Person.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Book.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Category.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Employee.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Fruit.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/EmployeeRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/FruitRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/AccountApplication.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/HibernateUtil.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/Account.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-crud/src/main/resources/logback.xml create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/resources/application-batchinserts.properties create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/resources/application-test.properties create mode 100644 persistence-modules/spring-data-jpa-crud/src/test/resources/test-fruit-data.sql diff --git a/persistence-modules/spring-data-jpa-crud/README.md b/persistence-modules/spring-data-jpa-crud/README.md new file mode 100644 index 0000000000..dc0c78c87e --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/README.md @@ -0,0 +1,21 @@ +## Spring Data JPA - CRUD + +This module contains articles about CRUD operations in Spring Data JPA + +### Relevant Articles: +- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) +- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) +- [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) +- [Spring Data JPA Batch Inserts](https://www.baeldung.com/spring-data-jpa-batch-inserts) +- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) +- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) +- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-crud/pom.xml b/persistence-modules/spring-data-jpa-crud/pom.xml new file mode 100644 index 0000000000..1708d14fc2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + spring-data-jpa-crud + spring-data-jpa-crud + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + com.google.guava + guava + ${guava.version} + + + com.h2database + h2 + + + net.ttddyy + datasource-proxy + ${datasource-proxy.version} + + + org.postgresql + postgresql + + + com.h2database + h2 + runtime + + + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + + + + 1.4.1 + 21.0 + 1.12.2 + + + diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..ce10072031 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/Application.java @@ -0,0 +1,14 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java new file mode 100644 index 0000000000..504357db44 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java @@ -0,0 +1,53 @@ +package com.baeldung.batchinserts; + +import java.lang.reflect.Method; +import javax.sql.DataSource; +import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; +import org.springframework.util.ReflectionUtils; + +@Component +@Profile("batchinserts") +public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { + + @Override + public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { + return bean; + } + + @Override + public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { + if (bean instanceof DataSource) { + ProxyFactory factory = new ProxyFactory(bean); + factory.setProxyTargetClass(true); + factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); + return factory.getProxy(); + } + + return bean; + } + + private static class ProxyDataSourceInterceptor implements MethodInterceptor { + + private final DataSource dataSource; + + public ProxyDataSourceInterceptor(final DataSource dataSource) { + this.dataSource = ProxyDataSourceBuilder.create(dataSource).name("Batch-Insert-Logger").asJson().countQuery().logQueryToSysOut().build(); + } + + @Override + public Object invoke(final MethodInvocation invocation) throws Throwable { + Method proxyMethod = ReflectionUtils.findMethod(dataSource.getClass(), invocation.getMethod().getName()); + if (proxyMethod != null) { + return proxyMethod.invoke(dataSource, invocation.getArguments()); + } + return invocation.proceed(); + } + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/School.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/School.java new file mode 100644 index 0000000000..6d2f333ac7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/School.java @@ -0,0 +1,45 @@ +package com.baeldung.batchinserts.model; + +import java.util.List; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class School { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @OneToMany(mappedBy = "school") + private List students; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getStudents() { + return students; + } + + public void setStudents(List students) { + this.students = students; + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/Student.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/Student.java new file mode 100644 index 0000000000..d38214f122 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/batchinserts/model/Student.java @@ -0,0 +1,44 @@ +package com.baeldung.batchinserts.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Student { + + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private long id; + + private String name; + + @ManyToOne + private School school; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public School getSchool() { + return school; + } + + public void setSchool(School school) { + this.school = school; + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..aaca760499 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("com.baeldung") +@EntityScan("com.baeldung") +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/CustomerRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/CustomerRepository.java new file mode 100644 index 0000000000..7cb7e45b27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/CustomerRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.boot.domain.Customer; + +/** + * JPA CrudRepository interface + * + * @author ysharma2512 + * + */ +@Repository +@Transactional +public interface CustomerRepository extends CrudRepository{ + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java new file mode 100644 index 0000000000..373532e1c3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java @@ -0,0 +1,31 @@ +package com.baeldung.boot.daos.impl; + +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.domain.Person; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; + +@Repository +public class PersonInsertRepository { + + @PersistenceContext + private EntityManager entityManager; + + @Transactional + public void insertWithQuery(Person person) { + entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)") + .setParameter(1, person.getId()) + .setParameter(2, person.getFirstName()) + .setParameter(3, person.getLastName()) + .executeUpdate(); + } + + @Transactional + public void insertWithEntityManager(Person person) { + this.entityManager.persist(person); + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Customer.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Customer.java new file mode 100644 index 0000000000..af88be0be6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Customer.java @@ -0,0 +1,56 @@ +package com.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +/** + * Customer Entity class + * @author ysharma2512 + * + */ +@Entity +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String firstName; + private String lastName; + + public Customer(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Person.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Person.java new file mode 100644 index 0000000000..88894ccc72 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/domain/Person.java @@ -0,0 +1,47 @@ +package com.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + + @Id + private Long id; + private String firstName; + private String lastName; + + public Person() { + } + + public Person(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java new file mode 100644 index 0000000000..e13afd9b45 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java @@ -0,0 +1,41 @@ +package com.baeldung.boot.web.controllers; + +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.List; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.boot.daos.CustomerRepository; +import com.baeldung.boot.domain.Customer; + +/** + * A simple controller to test the JPA CrudRepository operations + * controllers + * + * @author ysharma2512 + * + */ +@RestController +public class CustomerController { + + CustomerRepository customerRepository; + + public CustomerController(CustomerRepository customerRepository2) { + this.customerRepository = customerRepository2; + } + + @PostMapping("/customers") + public ResponseEntity> insertCustomers() throws URISyntaxException { + Customer c1 = new Customer("James", "Gosling"); + Customer c2 = new Customer("Doug", "Lea"); + Customer c3 = new Customer("Martin", "Fowler"); + Customer c4 = new Customer("Brian", "Goetz"); + List customers = Arrays.asList(c1, c2, c3, c4); + customerRepository.saveAll(customers); + return ResponseEntity.ok(customers); + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Book.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Book.java new file mode 100644 index 0000000000..deac24548a --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Book.java @@ -0,0 +1,51 @@ +package com.baeldung.datajpadelete.entity; + +import javax.persistence.*; + +@Entity +public class Book { + + @Id + @GeneratedValue + private Long id; + private String title; + + @ManyToOne + private Category category; + + public Book() { + } + + public Book(String title) { + this.title = title; + } + + public Book(String title, Category category) { + this.title = title; + this.category = category; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Category.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Category.java new file mode 100644 index 0000000000..16f1a4157f --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/entity/Category.java @@ -0,0 +1,60 @@ +package com.baeldung.datajpadelete.entity; + +import javax.persistence.*; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Entity +public class Category { + + @Id + @GeneratedValue + private Long id; + private String name; + + @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) + private List books; + + public Category() { + } + + public Category(String name) { + this.name = name; + } + + public Category(String name, Book... books) { + this.name = name; + this.books = Stream.of(books).collect(Collectors.toList()); + this.books.forEach(x -> x.setCategory(this)); + } + + public Category(String name, List books) { + this.name = name; + this.books = books; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java new file mode 100644 index 0000000000..5d0f45f127 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.datajpadelete.repository; + +import com.baeldung.datajpadelete.entity.Book; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +public interface BookRepository extends CrudRepository { + + long deleteByTitle(String title); + + @Modifying + @Query("delete from Book b where b.title=:title") + void deleteBooks(@Param("title") String title); + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java new file mode 100644 index 0000000000..6fe7058a78 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.datajpadelete.repository; + +import com.baeldung.datajpadelete.entity.Category; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface CategoryRepository extends CrudRepository { +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Employee.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Employee.java new file mode 100644 index 0000000000..4c3dbd25b7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Employee.java @@ -0,0 +1,36 @@ +package com.baeldung.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private Long id; + private String name; + + public Employee() { + } + + public Employee(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Fruit.java new file mode 100644 index 0000000000..d45ac33db8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/entity/Fruit.java @@ -0,0 +1,40 @@ +package com.baeldung.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +@Entity +public class Fruit { + + @Id + private long id; + private String name; + private String color; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/EmployeeRepository.java new file mode 100644 index 0000000000..8f0a80814b --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/EmployeeRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.repository; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.entity.Employee; + +public interface EmployeeRepository extends JpaRepository { + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/FruitRepository.java new file mode 100644 index 0000000000..5055252adf --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/repository/FruitRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.entity.Fruit; + +@Repository +public interface FruitRepository extends JpaRepository { + + Long deleteByName(String name); + + List deleteByColor(String color); + + Long removeByName(String name); + + List removeByColor(String color); + + @Modifying + @Query("delete from Fruit f where f.name=:name or f.color=:color") + int deleteFruits(@Param("name") String name, @Param("color") String color); +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/AccountApplication.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/AccountApplication.java new file mode 100644 index 0000000000..547992a6c1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/AccountApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.schemageneration; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AccountApplication { + + public static void main(String[] args) { + SpringApplication.run(AccountApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/HibernateUtil.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/HibernateUtil.java new file mode 100644 index 0000000000..7d69d65705 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/HibernateUtil.java @@ -0,0 +1,39 @@ +package com.baeldung.schemageneration; + +import com.baeldung.schemageneration.model.Account; +import com.baeldung.schemageneration.model.AccountSetting; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Environment; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.tool.schema.TargetType; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; + +public class HibernateUtil { + + /** + * Generates database create commands for the specified entities using Hibernate native API, SchemaExport. + * Creation commands are exported into the create.sql file. + */ + public static void generateSchema() { + Map settings = new HashMap<>(); + settings.put(Environment.URL, "jdbc:h2:mem:schema"); + + StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); + + MetadataSources metadataSources = new MetadataSources(serviceRegistry); + metadataSources.addAnnotatedClass(Account.class); + metadataSources.addAnnotatedClass(AccountSetting.class); + Metadata metadata = metadataSources.buildMetadata(); + + SchemaExport schemaExport = new SchemaExport(); + schemaExport.setFormat(true); + schemaExport.setOutputFile("create.sql"); + schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/Account.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/Account.java new file mode 100644 index 0000000000..785e275e26 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/Account.java @@ -0,0 +1,74 @@ +package com.baeldung.schemageneration.model; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "accounts") +public class Account { + + @Id + @GeneratedValue + private Long id; + + @Column(nullable = false, length = 100) + private String name; + + @Column(name = "email_address") + private String emailAddress; + + @OneToMany(mappedBy = "account", cascade = CascadeType.ALL) + private List accountSettings = new ArrayList<>(); + + public Account() { + } + + public Account(String name, String emailAddress) { + this.name = name; + this.emailAddress = emailAddress; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public List getAccountSettings() { + return accountSettings; + } + + public void setAccountSettings(List accountSettings) { + this.accountSettings = accountSettings; + } + + public void addAccountSetting(AccountSetting setting) { + this.accountSettings.add(setting); + setting.setAccount(this); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java new file mode 100644 index 0000000000..61e43894a8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java @@ -0,0 +1,68 @@ +package com.baeldung.schemageneration.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "account_settings") +public class AccountSetting { + + @Id + @GeneratedValue + private Long id; + + @Column(name = "name", nullable = false) + private String settingName; + + @Column(name = "value", nullable = false) + private String settingValue; + + @ManyToOne() + @JoinColumn(name ="account_id", nullable = false) + private Account account; + + public AccountSetting() { + } + + public AccountSetting(String settingName, String settingValue) { + this.settingName = settingName; + this.settingValue = settingValue; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSettingName() { + return settingName; + } + + public void setSettingName(String settingName) { + this.settingName = settingName; + } + + public String getSettingValue() { + return settingValue; + } + + public void setSettingValue(String settingValue) { + this.settingValue = settingValue; + } + + public Account getAccount() { + return account; + } + + public void setAccount(Account account) { + this.account = account; + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java new file mode 100644 index 0000000000..dc57ffe6d3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.schemageneration.repository; + +import com.baeldung.schemageneration.model.Account; +import org.springframework.data.repository.CrudRepository; + +public interface AccountRepository extends CrudRepository { + Account findByName(String name); +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java new file mode 100644 index 0000000000..c2b8ff7398 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.schemageneration.repository; + +import com.baeldung.schemageneration.model.AccountSetting; +import org.springframework.data.repository.CrudRepository; + +public interface AccountSettingRepository extends CrudRepository { + AccountSetting findByAccountId(Long accountId); +} diff --git a/persistence-modules/spring-data-jpa-crud/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-crud/src/main/resources/application.properties new file mode 100644 index 0000000000..af0df308cd --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/resources/application.properties @@ -0,0 +1,14 @@ +spring.main.allow-bean-definition-overriding=true + +spring.jpa.properties.hibernate.jdbc.batch_size=4 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.generate_statistics=true + +# JPA-Schema-Generation +# Use below configuration to generate database schema create commands based on the entity models +# and export them into the create.sql file +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata +#spring.jpa.properties.hibernate.format_sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa-crud/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..eaccf4acba --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java new file mode 100644 index 0000000000..27c71c5bcc --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java @@ -0,0 +1,19 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@DataJpaTest +@ContextConfiguration(classes = Application.class) +public class SpringJpaContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java new file mode 100644 index 0000000000..7ddf36d3f0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.batchinserts; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.baeldung.boot.Application; +import com.baeldung.boot.daos.CustomerRepository; +import com.baeldung.boot.web.controllers.CustomerController; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=Application.class) +@AutoConfigureMockMvc +public class BatchInsertIntegrationTest { + + @Autowired + private CustomerRepository customerRepository; + private MockMvc mockMvc; + @Before + public void setUp() throws Exception { + mockMvc = MockMvcBuilders.standaloneSetup( new CustomerController(customerRepository)) + .build(); + } + + @Test + public void whenInsertingCustomers_thenCustomersAreCreated() throws Exception { + this.mockMvc.perform(post("/customers")) + .andExpect(status().isOk()); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java new file mode 100644 index 0000000000..311f227322 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java @@ -0,0 +1,98 @@ +package com.baeldung.batchinserts; + +import static com.baeldung.batchinserts.TestObjectHelper.createSchool; +import static com.baeldung.batchinserts.TestObjectHelper.createStudent; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.batchinserts.model.School; +import com.baeldung.batchinserts.model.Student; +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@Transactional +@ActiveProfiles("batchinserts") +public class JpaBatchInsertsIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + private static final int BATCH_SIZE = 5; + + @Transactional + @Test + public void whenInsertingSingleTypeOfEntity_thenCreatesSingleBatch() { + for (int i = 0; i < 10; i++) { + School school = createSchool(i); + entityManager.persist(school); + } + } + + @Transactional + @Test + public void whenFlushingAfterBatch_ThenClearsMemory() { + for (int i = 0; i < 10; i++) { + if (i > 0 && i % BATCH_SIZE == 0) { + entityManager.flush(); + entityManager.clear(); + } + + School school = createSchool(i); + entityManager.persist(school); + } + } + + @Transactional + @Test + public void whenThereAreMultipleEntities_ThenCreatesNewBatch() { + for (int i = 0; i < 10; i++) { + if (i > 0 && i % BATCH_SIZE == 0) { + entityManager.flush(); + entityManager.clear(); + } + + School school = createSchool(i); + entityManager.persist(school); + Student firstStudent = createStudent(school); + Student secondStudent = createStudent(school); + entityManager.persist(firstStudent); + entityManager.persist(secondStudent); + } + } + + @Transactional + @Test + public void whenUpdatingEntities_thenCreatesBatch() { + for (int i = 0; i < 10; i++) { + School school = createSchool(i); + entityManager.persist(school); + } + + entityManager.flush(); + + TypedQuery schoolQuery = entityManager.createQuery("SELECT s from School s", School.class); + List allSchools = schoolQuery.getResultList(); + + for (School school : allSchools) { + school.setName("Updated_" + school.getName()); + } + } + + @After + public void tearDown() { + entityManager.flush(); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java new file mode 100644 index 0000000000..75b3f1f3aa --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.batchinserts; + +import static com.baeldung.batchinserts.TestObjectHelper.createSchool; + +import com.baeldung.batchinserts.model.School; +import com.baeldung.boot.Application; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@Transactional +@ActiveProfiles("batchinserts") +@TestPropertySource(properties = "spring.jpa.properties.hibernate.jdbc.batch_size=-1") +public class JpaNoBatchInsertsIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Test + public void whenNotConfigured_ThenSendsInsertsSeparately() { + for (int i = 0; i < 10; i++) { + School school = createSchool(i); + entityManager.persist(school); + } + } + + @After + public void tearDown() { + entityManager.flush(); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java new file mode 100644 index 0000000000..fcd26cb721 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java @@ -0,0 +1,20 @@ +package com.baeldung.batchinserts; + +import com.baeldung.batchinserts.model.School; +import com.baeldung.batchinserts.model.Student; + +public class TestObjectHelper { + + public static School createSchool(int nameIdentifier) { + School school = new School(); + school.setName("School" + (nameIdentifier + 1)); + return school; + } + + public static Student createStudent(School school) { + Student student = new Student(); + student.setName("Student-" + school.getName()); + student.setSchool(school); + return student; + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9d45c17035 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java @@ -0,0 +1,82 @@ +package com.baeldung.boot.daos; + +import com.baeldung.boot.daos.impl.PersonInsertRepository; +import com.baeldung.boot.domain.Person; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.persistence.EntityExistsException; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceException; + +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +@RunWith(SpringRunner.class) +@DataJpaTest +@Import(PersonInsertRepository.class) +public class PersonInsertRepositoryIntegrationTest { + + private static final Long ID = 1L; + private static final String FIRST_NAME = "firstname"; + private static final String LAST_NAME = "lastname"; + private static final Person PERSON = new Person(ID, FIRST_NAME, LAST_NAME); + + @Autowired + private PersonInsertRepository personInsertRepository; + + @Autowired + private EntityManager entityManager; + + @Test + public void givenPersonEntity_whenInsertWithNativeQuery_ThenPersonIsPersisted() { + insertWithQuery(); + + assertPersonPersisted(); + } + + @Test + public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenPersistenceExceptionExceptionIsThrown() { + assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { + insertWithQuery(); + insertWithQuery(); + }); + } + + @Test + public void givenPersonEntity_whenInsertWithEntityManager_thenPersonIsPersisted() { + insertPersonWithEntityManager(); + + assertPersonPersisted(); + } + + @Test + public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() { + assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> { + insertPersonWithEntityManager(); + insertPersonWithEntityManager(); + }); + } + + private void insertWithQuery() { + personInsertRepository.insertWithQuery(PERSON); + } + + private void insertPersonWithEntityManager() { + personInsertRepository.insertWithEntityManager(new Person(ID, FIRST_NAME, LAST_NAME)); + } + + private void assertPersonPersisted() { + Person person = entityManager.find(Person.class, ID); + + assertThat(person).isNotNull(); + assertThat(person.getId()).isEqualTo(PERSON.getId()); + assertThat(person.getFirstName()).isEqualTo(PERSON.getFirstName()); + assertThat(person.getLastName()).isEqualTo(PERSON.getLastName()); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java new file mode 100644 index 0000000000..5f4a36bc0e --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.datajpadelete; + +import com.baeldung.Application; +import com.baeldung.datajpadelete.entity.Book; +import com.baeldung.datajpadelete.repository.BookRepository; +import org.junit.After; +import org.junit.Before; +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 org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {Application.class}) +public class DeleteFromRepositoryUnitTest { + + @Autowired + private BookRepository repository; + + Book book1; + Book book2; + + @Before + public void setup() { + book1 = new Book("The Hobbit"); + book2 = new Book("All Quiet on the Western Front"); + + repository.saveAll(Arrays.asList(book1, book2)); + } + + @After + public void teardown() { + repository.deleteAll(); + } + + @Test + public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() { + repository.deleteById(book1.getId()); + + assertThat(repository.count()).isEqualTo(1); + } + + @Test + public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() { + repository.deleteAll(); + + assertThat(repository.count()).isEqualTo(0); + } + + @Test + @Transactional + public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() { + long deletedRecords = repository.deleteByTitle("The Hobbit"); + + assertThat(deletedRecords).isEqualTo(1); + } + + @Test + @Transactional + public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() { + repository.deleteBooks("The Hobbit"); + + assertThat(repository.count()).isEqualTo(1); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java new file mode 100644 index 0000000000..6275ace6e0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java @@ -0,0 +1,60 @@ +package com.baeldung.datajpadelete; + +import com.baeldung.Application; +import com.baeldung.datajpadelete.entity.Book; +import com.baeldung.datajpadelete.entity.Category; +import com.baeldung.datajpadelete.repository.BookRepository; +import com.baeldung.datajpadelete.repository.CategoryRepository; +import org.junit.After; +import org.junit.Before; +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.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {Application.class}) +public class DeleteInRelationshipsUnitTest { + + @Autowired + private BookRepository bookRepository; + + @Autowired + private CategoryRepository categoryRepository; + + @Before + public void setup() { + Book book1 = new Book("The Hobbit"); + Category category1 = new Category("Cat1", book1); + categoryRepository.save(category1); + + Book book2 = new Book("All Quiet on the Western Front"); + Category category2 = new Category("Cat2", book2); + categoryRepository.save(category2); + } + + @After + public void teardown() { + bookRepository.deleteAll(); + categoryRepository.deleteAll(); + } + + @Test + public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() { + categoryRepository.deleteAll(); + + assertThat(bookRepository.count()).isEqualTo(0); + assertThat(categoryRepository.count()).isEqualTo(0); + } + + @Test + public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() { + bookRepository.deleteAll(); + + assertThat(bookRepository.count()).isEqualTo(0); + assertThat(categoryRepository.count()).isEqualTo(2); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java new file mode 100644 index 0000000000..0fc9918701 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.repository; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +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 com.baeldung.boot.Application; +import com.baeldung.entity.Employee; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class EmployeeRepositoryIntegrationTest { + + private static final Employee EMPLOYEE1 = new Employee(1L, "John"); + private static final Employee EMPLOYEE2 = new Employee(2L, "Alice"); + + @Autowired + private EmployeeRepository employeeRepository; + + @Test + public void givenEmployeeEntity_whenInsertWithSave_ThenEmployeeIsPersisted() { + employeeRepository.save(EMPLOYEE1); + assertEmployeePersisted(EMPLOYEE1); + } + + @Test + public void givenEmployeeEntity_whenInsertWithSaveAndFlush_ThenEmployeeIsPersisted() { + employeeRepository.saveAndFlush(EMPLOYEE2); + assertEmployeePersisted(EMPLOYEE2); + } + + private void assertEmployeePersisted(Employee input) { + Employee employee = employeeRepository.getOne(input.getId()); + assertThat(employee).isNotNull(); + } +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java new file mode 100644 index 0000000000..cf771dc833 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.repository; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +import org.junit.jupiter.api.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.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.entity.Fruit; + +@RunWith(SpringRunner.class) +@SpringBootTest +class FruitRepositoryIntegrationTest { + + @Autowired + private FruitRepository fruitRepository; + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByColor_ThenDeletedFruitsShouldReturn() { + + List fruits = fruitRepository.deleteByColor("green"); + + assertEquals("number of fruits are not matching", 2, fruits.size()); + fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByName_ThenDeletedFruitCountShouldReturn() { + + Long deletedFruitCount = fruitRepository.deleteByName("apple"); + + assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenRemovedByColor_ThenDeletedFruitsShouldReturn() { + + List fruits = fruitRepository.removeByColor("green"); + + assertEquals("number of fruits are not matching", 2, fruits.size()); + fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenRemovedByName_ThenDeletedFruitCountShouldReturn() { + + Long deletedFruitCount = fruitRepository.removeByName("apple"); + + assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); + } + + @Transactional + @Test + @Sql(scripts = { "/test-fruit-data.sql" }) + public void givenFruits_WhenDeletedByColorOrName_ThenDeletedFruitsShouldReturn() { + + int deletedCount = fruitRepository.deleteFruits("apple", "green"); + + assertEquals("number of fruits are not matching", 3, deletedCount); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java new file mode 100644 index 0000000000..86a7671fe4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java @@ -0,0 +1,72 @@ +package com.baeldung.schemageneration; + +import com.baeldung.schemageneration.model.Account; +import com.baeldung.schemageneration.model.AccountSetting; +import com.baeldung.schemageneration.repository.AccountRepository; +import com.baeldung.schemageneration.repository.AccountSettingRepository; +import org.junit.After; +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.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = AccountApplication.class) +public class AccountRepositoryIntegrationTest { + + private static final String USER_NAME = "Eduard"; + private static final String USER_EMAIL_ADDRESS = "eduard@gmx.com"; + private static final String ACCOUNT_SETTING_NAME = "Timezone"; + private static final String ACCOUNT_SETTING_VALUE = "UTC+02"; + + @Autowired + private AccountRepository accountRepository; + + @Autowired + private AccountSettingRepository accountSettingRepository; + + @After + public void tearDown() { + accountRepository.deleteAll(); + } + + @Test + public void givenNewAccount_whenSave_thenSuccess() { + Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); + accountRepository.save(account); + + assertEquals(1, accountRepository.count()); + } + + @Test + public void givenSavedAccount_whenFindByName_thenFound() { + Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); + accountRepository.save(account); + + Account accountFound = accountRepository.findByName(USER_NAME); + + assertNotNull(accountFound); + assertEquals(USER_NAME, accountFound.getName()); + assertEquals(USER_EMAIL_ADDRESS, accountFound.getEmailAddress()); + } + + @Test + public void givenSavedAccount_whenAccountSettingIsAdded_thenPersisted() { + Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); + account.addAccountSetting(new AccountSetting(ACCOUNT_SETTING_NAME, ACCOUNT_SETTING_VALUE)); + accountRepository.save(account); + + Account accountFound = accountRepository.findByName(USER_NAME); + assertNotNull(accountFound); + AccountSetting accountSetting = accountSettingRepository.findByAccountId(accountFound.getId()); + + assertNotNull(accountSetting); + assertEquals(ACCOUNT_SETTING_NAME, accountSetting.getSettingName()); + assertEquals(ACCOUNT_SETTING_VALUE, accountSetting.getSettingValue()); + } + +} diff --git a/persistence-modules/spring-data-jpa-crud/src/test/resources/application-batchinserts.properties b/persistence-modules/spring-data-jpa-crud/src/test/resources/application-batchinserts.properties new file mode 100644 index 0000000000..4141f5668e --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/resources/application-batchinserts.properties @@ -0,0 +1,6 @@ +spring.jpa.show-sql=false + +spring.jpa.properties.hibernate.jdbc.batch_size=5 +spring.jpa.properties.hibernate.order_inserts=true +spring.jpa.properties.hibernate.order_updates=true +spring.jpa.properties.hibernate.batch_versioned_data=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-crud/src/test/resources/application-test.properties new file mode 100644 index 0000000000..f9497c8f37 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud/src/test/resources/test-fruit-data.sql b/persistence-modules/spring-data-jpa-crud/src/test/resources/test-fruit-data.sql new file mode 100644 index 0000000000..d99f42e5a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-crud/src/test/resources/test-fruit-data.sql @@ -0,0 +1,6 @@ +truncate table fruit; + +insert into fruit(id,name,color) values (1,'apple','red'); +insert into fruit(id,name,color) values (2,'custard apple','green'); +insert into fruit(id,name,color) values (3,'mango','yellow'); +insert into fruit(id,name,color) values (4,'guava','green'); \ No newline at end of file From 2f815070760802c98023faff9969e8483d6e4661 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:30:26 +0530 Subject: [PATCH 053/155] JAVA-66: New module spring-data-jpa-enterprise --- .../spring-data-jpa-enterprise/README.md | 24 + .../spring-data-jpa-enterprise/pom.xml | 107 ++++ .../main/java/com/baeldung/Application.java | 13 + .../java/com/baeldung/boot/Application.java | 17 + .../boot/config/PersistenceConfiguration.java | 23 + .../boot/daos/IBarCrudRepository.java | 11 + .../java/com/baeldung/boot/daos/IFooDao.java | 13 + .../boot/daos/user/UserRepository.java | 99 ++++ .../boot/daos/user/UserRepositoryCustom.java | 14 + .../daos/user/UserRepositoryCustomImpl.java | 57 ++ .../java/com/baeldung/boot/domain/Bar.java | 220 +++++++ .../java/com/baeldung/boot/domain/Foo.java | 94 +++ .../com/baeldung/boot/domain/Possession.java | 83 +++ .../java/com/baeldung/boot/domain/User.java | 132 +++++ .../baeldung/boot/services/IBarService.java | 7 + .../baeldung/boot/services/IFooService.java | 14 + .../baeldung/boot/services/IOperations.java | 26 + .../boot/services/impl/AbstractService.java | 61 ++ .../impl/AbstractSpringDataJpaService.java | 45 ++ .../impl/BarSpringDataJpaService.java | 31 + .../boot/services/impl/FooService.java | 55 ++ .../ElementCollectionApplication.java | 11 + .../elementcollection/model/Employee.java | 68 +++ .../elementcollection/model/Phone.java | 62 ++ .../repository/EmployeeRepository.java | 46 ++ .../multipledb/MultipleDbApplication.java | 14 + .../PersistenceProductAutoConfiguration.java | 71 +++ .../PersistenceProductConfiguration.java | 68 +++ .../PersistenceUserAutoConfiguration.java | 75 +++ .../PersistenceUserConfiguration.java | 69 +++ .../dao/product/ProductRepository.java | 14 + .../dao/user/PossessionRepository.java | 9 + .../multipledb/dao/user/UserRepository.java | 8 + .../multipledb/model/product/Product.java | 67 +++ .../model/user/PossessionMultipleDB.java | 82 +++ .../multipledb/model/user/UserMultipleDB.java | 88 +++ .../com/baeldung/namingstrategy/Person.java | 35 ++ .../namingstrategy/PersonRepository.java | 6 + .../QuotedLowerCaseNamingStrategy.java | 12 + .../QuotedUpperCaseNamingStrategy.java | 12 + ...ingDataJpaNamingConventionApplication.java | 7 + .../UnquotedLowerCaseNamingStrategy.java | 12 + .../UnquotedUpperCaseNamingStrategy.java | 12 + .../com/baeldung/osiv/OsivApplication.java | 13 + .../com/baeldung/osiv/model/BasicUser.java | 42 ++ .../osiv/repository/BasicUserRepository.java | 19 + .../osiv/service/SimpleUserService.java | 25 + .../baeldung/osiv/service/UserService.java | 9 + .../baeldung/osiv/web/DetailedUserDto.java | 45 ++ .../com/baeldung/osiv/web/UserController.java | 27 + .../PartialUpdateApplication.java | 12 + .../partialupdate/model/ContactPhone.java | 22 + .../partialupdate/model/Customer.java | 23 + .../partialupdate/model/CustomerDto.java | 31 + .../model/CustomerStructured.java | 27 + .../repository/ContactPhoneRepository.java | 12 + .../repository/CustomerRepository.java | 18 + .../CustomerStructuredRepository.java | 11 + .../service/CustomerService.java | 87 +++ .../partialupdate/util/CustomerMapper.java | 15 + .../src/main/resources/application.properties | 16 + .../persistence-multiple-db-boot.properties | 11 + .../persistence-multiple-db.properties | 13 + .../java/com/baeldung/SpringContextTest.java | 17 + .../SpringJpaContextIntegrationTest.java | 25 + .../boot/daos/UserRepositoryCommon.java | 545 ++++++++++++++++++ .../daos/UserRepositoryIntegrationTest.java | 37 ++ .../daos/UserRepositoryTCAutoLiveTest.java | 43 ++ .../boot/daos/UserRepositoryTCLiveTest.java | 58 ++ ...ractServicePersistenceIntegrationTest.java | 252 ++++++++ .../FooServicePersistenceIntegrationTest.java | 75 +++ .../SpringDataJPABarAuditIntegrationTest.java | 75 +++ .../ElementCollectionIntegrationTest.java | 64 ++ .../JpaMultipleDBIntegrationTest.java | 96 +++ .../ProductRepositoryIntegrationTest.java | 144 +++++ ...erCaseNamingStrategyH2IntegrationTest.java | 81 +++ ...werCaseNamingStrategyPostgresLiveTest.java | 85 +++ ...erCaseNamingStrategyH2IntegrationTest.java | 85 +++ ...perCaseNamingStrategyPostgresLiveTest.java | 81 +++ ...ysicalNamingStrategyH2IntegrationTest.java | 85 +++ ...hysicalNamingStrategyPostgresLiveTest.java | 85 +++ ...erCaseNamingStrategyH2IntegrationTest.java | 86 +++ ...werCaseNamingStrategyPostgresLiveTest.java | 85 +++ ...erCaseNamingStrategyH2IntegrationTest.java | 85 +++ ...perCaseNamingStrategyPostgresLiveTest.java | 85 +++ .../osiv/UserControllerIntegrationTest.java | 56 ++ .../partialupdate/PartialUpdateUnitTest.java | 63 ++ .../util/BaeldungPostgresqlContainer.java | 35 ++ .../test/java/com/baeldung/util/IDUtil.java | 33 ++ .../resources/application-test.properties | 3 + ...ase-naming-strategy-on-postgres.properties | 9 + ...oted-lower-case-naming-strategy.properties | 9 + ...ase-naming-strategy-on-postgres.properties | 9 + ...oted-upper-case-naming-strategy.properties | 9 + ...cal-naming-strategy-on-postgres.properties | 9 + ...spring-physical-naming-strategy.properties | 9 + ...ase-naming-strategy-on-postgres.properties | 9 + ...oted-lower-case-naming-strategy.properties | 9 + ...ase-naming-strategy-on-postgres.properties | 9 + ...oted-upper-case-naming-strategy.properties | 9 + 100 files changed, 5026 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-enterprise/README.md create mode 100644 persistence-modules/spring-data-jpa-enterprise/pom.xml create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/Application.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IFooDao.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Bar.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Foo.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Possession.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/User.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IBarService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IFooService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IOperations.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/FooService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java create mode 100755 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java create mode 100755 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/product/Product.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/PersonRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/OsivApplication.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/model/BasicUser.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/SimpleUserService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/UserService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/UserController.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/Customer.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/service/CustomerService.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db-boot.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/IDUtil.java create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/application-test.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties create mode 100644 persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/README.md b/persistence-modules/spring-data-jpa-enterprise/README.md new file mode 100644 index 0000000000..81398b1f00 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/README.md @@ -0,0 +1,24 @@ +## Spring Data JPA - Enterprise + +This module contains articles about Spring Data JPA used in enterprise applications such as transactions, sessions, naming conventions and more + +### Relevant Articles: + +- [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases) +- [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8) +- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) +- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) +- [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view) +- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) +- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) +- [Partial Data Update with Spring Data](https://www.baeldung.com/spring-data-partial-update) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/persistence-modules/spring-data-jpa-enterprise/pom.xml b/persistence-modules/spring-data-jpa-enterprise/pom.xml new file mode 100644 index 0000000000..093059ad78 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/pom.xml @@ -0,0 +1,107 @@ + + + + 4.0.0 + spring-data-jpa-enterprise + spring-data-jpa-enterprise + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + + org.springframework.boot + spring-boot-starter-cache + + + + com.h2database + h2 + + + + org.hibernate + hibernate-envers + + + + com.google.guava + guava + ${guava.version} + + + + org.mapstruct + mapstruct-jdk8 + ${mapstruct.version} + provided + + + + org.springframework.security + spring-security-test + test + + + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + + + + src/main/java + + + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + + + org.mapstruct + mapstruct-processor + 1.3.1.Final + + + + + + + + + 2.1.9.RELEASE + com.baeldung.springdatageode.app.ClientCacheApp + 1.1.1.RELEASE + 2.1.9.RELEASE + 1.3.1.Final + 21.0 + 1.12.2 + + + diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..3ea3d113da --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/Application.java new file mode 100644 index 0000000000..aaca760499 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/Application.java @@ -0,0 +1,17 @@ +package com.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("com.baeldung") +@EntityScan("com.baeldung") +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java new file mode 100644 index 0000000000..76d5887030 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.baeldung.boot.services.IBarService; +import com.baeldung.boot.services.impl.BarSpringDataJpaService; + +@Configuration +@Profile("!tc") +@EnableTransactionManagement +@EnableJpaAuditing +public class PersistenceConfiguration { + + @Bean + public IBarService barSpringDataJpaService() { + return new BarSpringDataJpaService(); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java new file mode 100644 index 0000000000..921fabe3fb --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.repository.CrudRepository; + +import com.baeldung.boot.domain.Bar; + +import java.io.Serializable; + +public interface IBarCrudRepository extends CrudRepository { + // +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IFooDao.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IFooDao.java new file mode 100644 index 0000000000..d537772076 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/IFooDao.java @@ -0,0 +1,13 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import com.baeldung.boot.domain.Foo; + +public interface IFooDao extends JpaRepository { + + @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") + Foo retrieveByName(@Param("name") String name); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java new file mode 100644 index 0000000000..53f692ff28 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepository.java @@ -0,0 +1,99 @@ +package com.baeldung.boot.daos.user; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import com.baeldung.boot.domain.User; + +import java.time.LocalDate; +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; + +public interface UserRepository extends JpaRepository , UserRepositoryCustom{ + + Stream findAllByName(String name); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @Query("select u from User u where u.email like '%@gmail.com'") + List findUsersWithGmailAddress(); + + @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true) + Collection findAllActiveUsersNative(); + + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) + User findUserByStatusNative(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); + + @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) + User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); + + @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") + User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); + + @Query("SELECT u FROM User u WHERE u.name like ?1%") + User findUserByNameLike(String name); + + @Query("SELECT u FROM User u WHERE u.name like :name%") + User findUserByNameLikeNamedParam(@Param("name") String name); + + @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) + User findUserByNameLikeNative(String name); + + @Query(value = "SELECT u FROM User u") + List findAllUsers(Sort sort); + + @Query(value = "SELECT u FROM User u ORDER BY id") + Page findAllUsersWithPagination(Pageable pageable); + + @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) + Page findAllUsersWithPaginationNative(Pageable pageable); + + @Modifying + @Query("update User u set u.status = :status where u.name = :name") + int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); + + @Modifying + @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNative(Integer status, String name); + + @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) + @Modifying + void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); + + @Modifying + @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) + int updateUserSetStatusForNameNativePostgres(Integer status, String name); + + @Query(value = "SELECT u FROM User u WHERE u.name IN :names") + List findUserByNameList(@Param("names") Collection names); + + void deleteAllByCreationDateAfter(LocalDate date); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query("update User u set u.active = false where u.lastLoginDate < :date") + void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query("delete User u where u.active = false") + int deleteDeactivatedUsers(); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) + void addDeletedColumn(); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java new file mode 100644 index 0000000000..c586b54027 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.daos.user; + +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import com.baeldung.boot.domain.User; + +public interface UserRepositoryCustom { + List findUserByEmails(Set emails); + + List findAllUsersByPredicates(Collection> predicates); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java new file mode 100644 index 0000000000..63a743b6b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java @@ -0,0 +1,57 @@ +package com.baeldung.boot.daos.user; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import com.baeldung.boot.domain.User; + +public class UserRepositoryCustomImpl implements UserRepositoryCustom { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findUserByEmails(Set emails) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(User.class); + Root user = query.from(User.class); + + Path emailPath = user.get("email"); + + List predicates = new ArrayList<>(); + for (String email : emails) { + + predicates.add(cb.like(emailPath, email)); + + } + query.select(user) + .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); + + return entityManager.createQuery(query) + .getResultList(); + } + + @Override + public List findAllUsersByPredicates(Collection> predicates) { + List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); + Stream allUsersStream = allUsers.stream(); + for (java.util.function.Predicate predicate : predicates) { + allUsersStream = allUsersStream.filter(predicate); + } + + return allUsersStream.collect(Collectors.toList()); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Bar.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Bar.java new file mode 100644 index 0000000000..35d1903801 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Bar.java @@ -0,0 +1,220 @@ +package com.baeldung.boot.domain; + +import com.google.common.collect.Sets; +import org.hibernate.annotations.OrderBy; +import org.hibernate.envers.Audited; +import org.jboss.logging.Logger; +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.Set; + +@Entity +@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") +@Audited +@EntityListeners(AuditingEntityListener.class) +public class Bar implements Serializable { + + private static Logger logger = Logger.getLogger(Bar.class); + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private int id; + + @Column(name = "name") + private String name; + @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) + @OrderBy(clause = "NAME DESC") + // @NotAudited + private Set fooSet = Sets.newHashSet(); + @Column(name = "operation") + private String operation; + @Column(name = "timestamp") + private long timestamp; + @Column(name = "created_date", updatable = false, nullable = false) + @CreatedDate + private long createdDate; + @Column(name = "modified_date") + @LastModifiedDate + private long modifiedDate; + @Column(name = "created_by") + @CreatedBy + private String createdBy; + @Column(name = "modified_by") + @LastModifiedBy + private String modifiedBy; + + public Bar() { + super(); + } + + public Bar(final String name) { + super(); + + this.name = name; + } + + public Set getFooSet() { + return fooSet; + } + + // API + + public void setFooSet(final Set fooSet) { + this.fooSet = fooSet; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public OPERATION getOperation() { + return OPERATION.parse(operation); + } + + public void setOperation(final String operation) { + this.operation = operation; + } + + public void setOperation(final OPERATION operation) { + this.operation = operation.getValue(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(final long timestamp) { + this.timestamp = timestamp; + } + + public long getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(final long createdDate) { + this.createdDate = createdDate; + } + + public long getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(final long modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(final String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(final String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Bar other = (Bar) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Bar [name=").append(name).append("]"); + return builder.toString(); + } + + @PrePersist + public void onPrePersist() { + logger.info("@PrePersist"); + audit(OPERATION.INSERT); + } + + @PreUpdate + public void onPreUpdate() { + logger.info("@PreUpdate"); + audit(OPERATION.UPDATE); + } + + @PreRemove + public void onPreRemove() { + logger.info("@PreRemove"); + audit(OPERATION.DELETE); + } + + private void audit(final OPERATION operation) { + setOperation(operation); + setTimestamp((new Date()).getTime()); + } + + public enum OPERATION { + INSERT, UPDATE, DELETE; + private String value; + + OPERATION() { + value = toString(); + } + + public static OPERATION parse(final String value) { + OPERATION operation = null; + for (final OPERATION op : OPERATION.values()) { + if (op.getValue().equals(value)) { + operation = op; + break; + } + } + return operation; + } + + public String getValue() { + return value; + } + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Foo.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Foo.java new file mode 100644 index 0000000000..5030e5600b --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Foo.java @@ -0,0 +1,94 @@ +package com.baeldung.boot.domain; + +import org.hibernate.envers.Audited; + +import javax.persistence.*; +import java.io.Serializable; + +@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)}) +@Entity +@Audited +// @Proxy(lazy = false) +public class Foo implements Serializable { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private long id; + + @Column(name = "name", nullable = false) + private String name; + + @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) + @JoinColumn(name = "BAR_ID") + private Bar bar = new Bar(); + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + this.name = name; + } + + // + + public Bar getBar() { + return bar; + } + + public void setBar(final Bar bar) { + this.bar = bar; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + // + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Possession.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Possession.java new file mode 100644 index 0000000000..f13491ad82 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/Possession.java @@ -0,0 +1,83 @@ +package com.baeldung.boot.domain; + +import javax.persistence.*; +import com.baeldung.boot.domain.Possession; + +@Entity +@Table +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/User.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/User.java new file mode 100644 index 0000000000..cca00e52a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/domain/User.java @@ -0,0 +1,132 @@ +package com.baeldung.boot.domain; + +import javax.persistence.*; + +import java.time.LocalDate; +import java.util.List; +import java.util.Objects; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + private LocalDate creationDate; + private LocalDate lastLoginDate; + private boolean active; + private int age; + @Column(unique = true, nullable = false) + private String email; + private Integer status; + @OneToMany + List possessionList; + + public User() { + super(); + } + + public User(String name, LocalDate creationDate,String email, Integer status) { + this.name = name; + this.creationDate = creationDate; + this.email = email; + this.status = status; + this.active = true; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + public LocalDate getCreationDate() { + return creationDate; + } + + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + User user = (User) o; + return id == user.id && + age == user.age && + Objects.equals(name, user.name) && + Objects.equals(creationDate, user.creationDate) && + Objects.equals(email, user.email) && + Objects.equals(status, user.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, creationDate, age, email, status); + } + + public LocalDate getLastLoginDate() { + return lastLoginDate; + } + + public void setLastLoginDate(LocalDate lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IBarService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IBarService.java new file mode 100644 index 0000000000..8054cbba59 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IBarService.java @@ -0,0 +1,7 @@ +package com.baeldung.boot.services; + +import com.baeldung.boot.domain.Bar; + +public interface IBarService extends IOperations { + // +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IFooService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IFooService.java new file mode 100644 index 0000000000..871cccdd45 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IFooService.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.services; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; + +import com.baeldung.boot.domain.Foo; + +public interface IFooService extends IOperations { + + Foo retrieveByName(String name); + + Page findPaginated(Pageable pageable); + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IOperations.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IOperations.java new file mode 100644 index 0000000000..ec2b866b6f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/IOperations.java @@ -0,0 +1,26 @@ +package com.baeldung.boot.services; + +import org.springframework.data.domain.Page; + +import java.io.Serializable; +import java.util.List; + +public interface IOperations { + + T findOne(final long id); + + List findAll(); + + Page findPaginated(int page, int size); + + // write + + T create(final T entity); + + T update(final T entity); + + void delete(final T entity); + + void deleteById(final long entityId); + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractService.java new file mode 100644 index 0000000000..f88d018bbb --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractService.java @@ -0,0 +1,61 @@ +package com.baeldung.boot.services.impl; + +import com.baeldung.boot.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional +public abstract class AbstractService implements IOperations { + + // read - one + + @Override + @Transactional(readOnly = true) + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + // read - all + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(final int page, final int size) { + return getDao().findAll(PageRequest.of(page, size)); + } + + // write + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract PagingAndSortingRepository getDao(); + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java new file mode 100644 index 0000000000..a73a6bd7fc --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java @@ -0,0 +1,45 @@ +package com.baeldung.boot.services.impl; + +import com.baeldung.boot.services.IOperations; +import com.google.common.collect.Lists; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.List; + +@Transactional(value = "transactionManager") +public abstract class AbstractSpringDataJpaService implements IOperations { + + @Override + public T findOne(final long id) { + return getDao().findById(id).orElse(null); + } + + @Override + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public T create(final T entity) { + return getDao().save(entity); + } + + @Override + public T update(final T entity) { + return getDao().save(entity); + } + + @Override + public void delete(final T entity) { + getDao().delete(entity); + } + + @Override + public void deleteById(final long entityId) { + getDao().deleteById(entityId); + } + + protected abstract CrudRepository getDao(); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java new file mode 100644 index 0000000000..80568f2fd4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java @@ -0,0 +1,31 @@ +package com.baeldung.boot.services.impl; + +import com.baeldung.boot.daos.IBarCrudRepository; +import com.baeldung.boot.domain.Bar; +import com.baeldung.boot.services.IBarService; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.repository.CrudRepository; + +import java.io.Serializable; + +public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { + + @Autowired + private IBarCrudRepository dao; + + public BarSpringDataJpaService() { + super(); + } + + @Override + protected CrudRepository getDao() { + return dao; + } + + @Override + public Page findPaginated(int page, int size) { + throw new UnsupportedOperationException("Not implemented yet"); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/FooService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/FooService.java new file mode 100644 index 0000000000..04eec63854 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/boot/services/impl/FooService.java @@ -0,0 +1,55 @@ +package com.baeldung.boot.services.impl; + +import com.google.common.collect.Lists; +import com.baeldung.boot.daos.IFooDao; +import com.baeldung.boot.domain.Foo; +import com.baeldung.boot.services.IFooService; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@Service +@Transactional +public class FooService extends AbstractService implements IFooService { + + @Autowired + private IFooDao dao; + + public FooService() { + super(); + } + + // API + + @Override + protected PagingAndSortingRepository getDao() { + return dao; + } + + // custom methods + + @Override + public Foo retrieveByName(final String name) { + return dao.retrieveByName(name); + } + + // overridden to be secured + + @Override + @Transactional(readOnly = true) + public List findAll() { + return Lists.newArrayList(getDao().findAll()); + } + + @Override + public Page findPaginated(Pageable pageable) { + return dao.findAll(pageable); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java new file mode 100644 index 0000000000..3f152a6ffc --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.elementcollection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ElementCollectionApplication { + public static void main(String[] args) { + SpringApplication.run(ElementCollectionApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java new file mode 100644 index 0000000000..8b98164d63 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java @@ -0,0 +1,68 @@ +package com.baeldung.elementcollection.model; + +import javax.persistence.*; +import java.util.List; +import java.util.Objects; + +@Entity +public class Employee { + @Id + private int id; + private String name; + @ElementCollection + @CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id")) + private List phones; + + public Employee() { + } + + public Employee(int id) { + this.id = id; + } + + public Employee(int id, String name) { + this.id = id; + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getPhones() { + return phones; + } + + public void setPhones(List phones) { + this.phones = phones; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Employee)) { + return false; + } + Employee user = (Employee) o; + return getId() == user.getId(); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java new file mode 100644 index 0000000000..d73d30c47a --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java @@ -0,0 +1,62 @@ +package com.baeldung.elementcollection.model; + +import javax.persistence.Embeddable; +import java.util.Objects; + +@Embeddable +public class Phone { + private String type; + private String areaCode; + private String number; + + public Phone() { + } + + public Phone(String type, String areaCode, String number) { + this.type = type; + this.areaCode = areaCode; + this.number = number; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAreaCode() { + return areaCode; + } + + public void setAreaCode(String areaCode) { + this.areaCode = areaCode; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Phone)) { + return false; + } + Phone phone = (Phone) o; + return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode()) + && getNumber().equals(phone.getNumber()); + } + + @Override + public int hashCode() { + return Objects.hash(getType(), getAreaCode(), getNumber()); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java new file mode 100644 index 0000000000..49180c35eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java @@ -0,0 +1,46 @@ +package com.baeldung.elementcollection.repository; + +import com.baeldung.elementcollection.model.Employee; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityGraph; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.HashMap; +import java.util.Map; + +@Repository +public class EmployeeRepository { + + @PersistenceContext + private EntityManager em; + + @Transactional + public void save(Employee employee) { + em.persist(employee); + } + + @Transactional + public void remove(int id) { + Employee employee = findById(id); + em.remove(employee); + } + + public Employee findById(int id) { + return em.find(Employee.class, id); + } + + public Employee findByJPQL(int id) { + return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class) + .setParameter("id", id).getSingleResult(); + } + + public Employee findByEntityGraph(int id) { + EntityGraph entityGraph = em.createEntityGraph(Employee.class); + entityGraph.addAttributeNodes("name", "phones"); + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + return em.find(Employee.class, id, properties); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java new file mode 100644 index 0000000000..3b9aa2cc18 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.multipledb; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MultipleDbApplication { + + public static void main(String[] args) { + SpringApplication.run(MultipleDbApplication.class, args); + } + +} + diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java new file mode 100644 index 0000000000..a6f8f0829f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java @@ -0,0 +1,71 @@ +package com.baeldung.multipledb; + +import java.util.HashMap; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * By default, the persistence-multiple-db.properties file is read for + * non auto configuration in PersistenceProductConfiguration. + *

+ * If we need to use persistence-multiple-db-boot.properties and auto configuration + * then uncomment the below @Configuration class and comment out PersistenceProductConfiguration. + */ +//@Configuration +@PropertySource({"classpath:persistence-multiple-db-boot.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +@Profile("!tc") +public class PersistenceProductAutoConfiguration { + @Autowired + private Environment env; + + public PersistenceProductAutoConfiguration() { + super(); + } + + // + + @Bean + public LocalContainerEntityManagerFactoryBean productEntityManager() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(productDataSource()); + em.setPackagesToScan("com.baeldung.multipledb.model.product"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Bean + @ConfigurationProperties(prefix="spring.second-datasource") + public DataSource productDataSource() { + return DataSourceBuilder.create().build(); + } + + @Bean + public PlatformTransactionManager productTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(productEntityManager().getObject()); + return transactionManager; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java new file mode 100644 index 0000000000..bcf2cd84eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java @@ -0,0 +1,68 @@ +package com.baeldung.multipledb; + +import com.google.common.base.Preconditions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; + +@Configuration +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +@Profile("!tc") +public class PersistenceProductConfiguration { + @Autowired + private Environment env; + + public PersistenceProductConfiguration() { + super(); + } + + // + + @Bean + public LocalContainerEntityManagerFactoryBean productEntityManager() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(productDataSource()); + em.setPackagesToScan("com.baeldung.multipledb.model.product"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Bean + public DataSource productDataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager productTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(productEntityManager().getObject()); + return transactionManager; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java new file mode 100644 index 0000000000..e04a1621b2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java @@ -0,0 +1,75 @@ +package com.baeldung.multipledb; + +import java.util.HashMap; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.jdbc.DataSourceBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * By default, the persistence-multiple-db.properties file is read for + * non auto configuration in PersistenceUserConfiguration. + *

+ * If we need to use persistence-multiple-db-boot.properties and auto configuration + * then uncomment the below @Configuration class and comment out PersistenceUserConfiguration. + */ +//@Configuration +@PropertySource({"classpath:persistence-multiple-db-boot.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +@Profile("!tc") +public class PersistenceUserAutoConfiguration { + @Autowired + private Environment env; + + public PersistenceUserAutoConfiguration() { + super(); + } + + // + + @Primary + @Bean + public LocalContainerEntityManagerFactoryBean userEntityManager() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(userDataSource()); + em.setPackagesToScan("com.baeldung.multipledb.model.user"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Bean + @Primary + @ConfigurationProperties(prefix="spring.datasource") + public DataSource userDataSource() { + return DataSourceBuilder.create().build(); + } + + @Primary + @Bean + public PlatformTransactionManager userTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(userEntityManager().getObject()); + return transactionManager; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java new file mode 100644 index 0000000000..6b48455c0c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java @@ -0,0 +1,69 @@ +package com.baeldung.multipledb; + +import com.google.common.base.Preconditions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.*; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; + +@Configuration +@PropertySource({"classpath:persistence-multiple-db.properties"}) +@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") +@Profile("!tc") +public class PersistenceUserConfiguration { + @Autowired + private Environment env; + + public PersistenceUserConfiguration() { + super(); + } + + // + + @Primary + @Bean + public LocalContainerEntityManagerFactoryBean userEntityManager() { + System.out.println("loading config"); + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(userDataSource()); + em.setPackagesToScan("com.baeldung.multipledb.model.user"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Primary + @Bean + public DataSource userDataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Primary + @Bean + public PlatformTransactionManager userTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(userEntityManager().getObject()); + return transactionManager; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java new file mode 100755 index 0000000000..f1256e2c72 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.multipledb.dao.product; + +import java.util.List; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.PagingAndSortingRepository; + +import com.baeldung.multipledb.model.product.Product; + +public interface ProductRepository extends PagingAndSortingRepository { + + + List findAllByPrice(double price, Pageable pageable); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java new file mode 100644 index 0000000000..ae37fde20d --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.multipledb.dao.user; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.multipledb.model.user.PossessionMultipleDB; + +public interface PossessionRepository extends JpaRepository { + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java new file mode 100644 index 0000000000..267a61a93f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.multipledb.dao.user; + +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.multipledb.model.user.UserMultipleDB; + +public interface UserRepository extends JpaRepository { +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/product/Product.java new file mode 100755 index 0000000000..eaf471043c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/product/Product.java @@ -0,0 +1,67 @@ +package com.baeldung.multipledb.model.product; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(schema = "products") +public class Product { + + @Id + private int id; + + private String name; + + private double price; + + public Product() { + super(); + } + + private Product(int id, String name, double price) { + super(); + this.id = id; + this.name = name; + this.price = price; + } + + public static Product from(int id, String name, double price) { + return new Product(id, name, price); + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(final double price) { + this.price = price; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Product [name=") + .append(name) + .append(", id=") + .append(id) + .append("]"); + return builder.toString(); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java new file mode 100644 index 0000000000..a6a3c88bd0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java @@ -0,0 +1,82 @@ +package com.baeldung.multipledb.model.user; + +import javax.persistence.*; + +@Entity +@Table +public class PossessionMultipleDB { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public PossessionMultipleDB() { + super(); + } + + public PossessionMultipleDB(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final PossessionMultipleDB other = (PossessionMultipleDB) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java new file mode 100644 index 0000000000..c7cd07f7a1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java @@ -0,0 +1,88 @@ +package com.baeldung.multipledb.model.user; + +import javax.persistence.*; + +import java.util.List; + +@Entity +@Table(name = "users") +public class UserMultipleDB { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + private int age; + @Column(unique = true, nullable = false) + private String email; + private Integer status; + + @OneToMany + List possessionList; + + public UserMultipleDB() { + super(); + } + + public UserMultipleDB(String name, String email, Integer status) { + this.name = name; + this.email = email; + this.status = status; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java new file mode 100644 index 0000000000..cfb6e67c2c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java @@ -0,0 +1,35 @@ +package com.baeldung.namingstrategy; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Person { + @Id + private Long id; + + private String firstName; + + private String lastName; + + public Person() {} + + public Person(Long id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long id() { + return id; + } + + public String firstName() { + return firstName; + } + + public String lastName() { + return lastName; + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/PersonRepository.java new file mode 100644 index 0000000000..3c7c25bbcb --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/PersonRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.namingstrategy; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface PersonRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..16b01e50e3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..3cb62aa5a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), true); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java new file mode 100644 index 0000000000..f223015db8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java @@ -0,0 +1,7 @@ +package com.baeldung.namingstrategy; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringDataJpaNamingConventionApplication { +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java new file mode 100644 index 0000000000..69e96aee27 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toLowerCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java new file mode 100644 index 0000000000..cb87af10f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java @@ -0,0 +1,12 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; +import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; + +public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { + @Override + protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { + return new Identifier(name.toUpperCase(), false); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/OsivApplication.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/OsivApplication.java new file mode 100644 index 0000000000..4cfcf83e56 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/OsivApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.osiv; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class OsivApplication { + + public static void main(String[] args) { + SpringApplication.run(OsivApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/model/BasicUser.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/model/BasicUser.java new file mode 100644 index 0000000000..98f4e379d4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/model/BasicUser.java @@ -0,0 +1,42 @@ +package com.baeldung.osiv.model; + +import javax.persistence.*; +import java.util.Set; + +@Entity +@Table(name = "users") +public class BasicUser { + + @Id + @GeneratedValue + private Long id; + + private String username; + + @ElementCollection + private Set permissions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Set getPermissions() { + return permissions; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java new file mode 100644 index 0000000000..e8d5955d91 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.osiv.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.osiv.model.BasicUser; + +@Repository +@Transactional +public interface BasicUserRepository extends JpaRepository { + + @EntityGraph(attributePaths = "permissions") + Optional findDetailedByUsername(String username); + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/SimpleUserService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/SimpleUserService.java new file mode 100644 index 0000000000..1de51678d5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/SimpleUserService.java @@ -0,0 +1,25 @@ +package com.baeldung.osiv.service; + +import java.util.Optional; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.osiv.model.BasicUser; +import com.baeldung.osiv.repository.BasicUserRepository; + +@Service +public class SimpleUserService implements UserService { + + private final BasicUserRepository userRepository; + + public SimpleUserService(BasicUserRepository userRepository) { + this.userRepository = userRepository; + } + + @Override + @Transactional(readOnly = true) + public Optional findOne(String username) { + return userRepository.findDetailedByUsername(username); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/UserService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/UserService.java new file mode 100644 index 0000000000..3d089fa41b --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/service/UserService.java @@ -0,0 +1,9 @@ +package com.baeldung.osiv.service; + +import com.baeldung.osiv.model.BasicUser; + +import java.util.Optional; + +public interface UserService { + Optional findOne(String username); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java new file mode 100644 index 0000000000..fd2882c2d5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java @@ -0,0 +1,45 @@ +package com.baeldung.osiv.web; + +import com.baeldung.osiv.model.BasicUser; + +import java.util.Set; + +public class DetailedUserDto { + + private Long id; + private String username; + private Set permissions; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public Set getPermissions() { + return permissions; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } + + public static DetailedUserDto fromEntity(BasicUser user) { + DetailedUserDto detailed = new DetailedUserDto(); + detailed.setId(user.getId()); + detailed.setUsername(user.getUsername()); + detailed.setPermissions(user.getPermissions()); + + return detailed; + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/UserController.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/UserController.java new file mode 100644 index 0000000000..5466b95166 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/osiv/web/UserController.java @@ -0,0 +1,27 @@ +package com.baeldung.osiv.web; + +import com.baeldung.osiv.service.UserService; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/users") +public class UserController { + + private final UserService userService; + + public UserController(UserService userService) { + this.userService = userService; + } + + @GetMapping("/{username}") + public ResponseEntity findOne(@PathVariable String username) { + return userService.findOne(username) + .map(DetailedUserDto::fromEntity) + .map(ResponseEntity::ok) + .orElse(ResponseEntity.notFound().build()); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java new file mode 100644 index 0000000000..a750fcadf7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.partialupdate; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PartialUpdateApplication { + + public static void main(String[] args) { + SpringApplication.run(PartialUpdateApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java new file mode 100644 index 0000000000..352e361bd9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java @@ -0,0 +1,22 @@ +package com.baeldung.partialupdate.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class ContactPhone { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public long id; + @Column(nullable=false) + public long customerId; + public String phone; + + @Override + public String toString() { + return phone; + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/Customer.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/Customer.java new file mode 100644 index 0000000000..b19d0b7952 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/Customer.java @@ -0,0 +1,23 @@ +package com.baeldung.partialupdate.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Customer { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public long id; + public String name; + public String phone; + //... + public String phone99; + + @Override public String toString() { + return String.format("Customer %s, Phone: %s", + this.name, this.phone); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java new file mode 100644 index 0000000000..0ecf206d9a --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java @@ -0,0 +1,31 @@ +package com.baeldung.partialupdate.model; + +public class CustomerDto { + private long id; + public String name; + public String phone; + //... + private String phone99; + + public CustomerDto(long id) { + this.id = id; + } + + public CustomerDto(Customer c) { + this.id = c.id; + this.name = c.name; + this.phone = c.phone; + } + + public long getId() { + return this.id; + } + + public Customer convertToEntity() { + Customer c = new Customer(); + c.id = id; + c.name = name; + c.phone = phone; + return c; + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java new file mode 100644 index 0000000000..dd053a963d --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java @@ -0,0 +1,27 @@ +package com.baeldung.partialupdate.model; + +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class CustomerStructured { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + public long id; + public String name; + @OneToMany(fetch = FetchType.EAGER, targetEntity = ContactPhone.class, mappedBy = "customerId") + public List contactPhones; + + @Override public String toString() { + return String.format("Customer %s, Phone: %s", + this.name, this.contactPhones.stream() + .map(e -> e.toString()).reduce("", String::concat)); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java new file mode 100644 index 0000000000..4668181e05 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java @@ -0,0 +1,12 @@ +package com.baeldung.partialupdate.repository; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.partialupdate.model.ContactPhone; + +@Repository +public interface ContactPhoneRepository extends CrudRepository { + ContactPhone findById(long id); + ContactPhone findByCustomerId(long id); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java new file mode 100644 index 0000000000..43e61df8ab --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java @@ -0,0 +1,18 @@ +package com.baeldung.partialupdate.repository; + +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.partialupdate.model.Customer; + +@Repository +public interface CustomerRepository extends CrudRepository { + Customer findById(long id); + + @Modifying + @Query("update Customer u set u.phone = :phone where u.id = :id") + void updatePhone(@Param(value = "id") long id, @Param(value = "phone") String phone); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java new file mode 100644 index 0000000000..0f9fd1e92e --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.partialupdate.repository; + +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.partialupdate.model.CustomerStructured; + +@Repository +public interface CustomerStructuredRepository extends CrudRepository { + CustomerStructured findById(long id); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/service/CustomerService.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/service/CustomerService.java new file mode 100644 index 0000000000..9da97a7775 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/service/CustomerService.java @@ -0,0 +1,87 @@ +package com.baeldung.partialupdate.service; + +import javax.transaction.Transactional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.partialupdate.model.ContactPhone; +import com.baeldung.partialupdate.model.Customer; +import com.baeldung.partialupdate.model.CustomerDto; +import com.baeldung.partialupdate.model.CustomerStructured; +import com.baeldung.partialupdate.repository.ContactPhoneRepository; +import com.baeldung.partialupdate.repository.CustomerRepository; +import com.baeldung.partialupdate.repository.CustomerStructuredRepository; +import com.baeldung.partialupdate.util.CustomerMapper; + +@Service +@Transactional +public class CustomerService { + + @Autowired + CustomerRepository repo; + @Autowired + CustomerStructuredRepository repo2; + @Autowired + ContactPhoneRepository repo3; + @Autowired + CustomerMapper mapper; + + public Customer getCustomer(long id) { + return repo.findById(id); + } + + public void updateCustomerWithCustomQuery(long id, String phone) { + repo.updatePhone(id, phone); + } + + public Customer addCustomer(String name) { + Customer myCustomer = new Customer(); + myCustomer.name = name; + repo.save(myCustomer); + return myCustomer; + } + + public Customer updateCustomer(long id, String phone) { + Customer myCustomer = repo.findById(id); + myCustomer.phone = phone; + repo.save(myCustomer); + return myCustomer; + } + + public Customer addCustomer(CustomerDto dto) { + Customer myCustomer = new Customer(); + mapper.updateCustomerFromDto(dto, myCustomer); + repo.save(myCustomer); + return myCustomer; + } + + public Customer updateCustomer(CustomerDto dto) { + Customer myCustomer = repo.findById(dto.getId()); + mapper.updateCustomerFromDto(dto, myCustomer); + repo.save(myCustomer); + return myCustomer; + } + + public CustomerStructured addCustomerStructured(String name) { + CustomerStructured myCustomer = new CustomerStructured(); + myCustomer.name = name; + repo2.save(myCustomer); + return myCustomer; + } + + public void addCustomerPhone(long customerId, String phone) { + ContactPhone myPhone = new ContactPhone(); + myPhone.phone = phone; + myPhone.customerId = customerId; + repo3.save(myPhone); + } + + public CustomerStructured updateCustomerStructured(long id, String name) { + CustomerStructured myCustomer = repo2.findById(id); + myCustomer.name = name; + repo2.save(myCustomer); + return myCustomer; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java new file mode 100644 index 0000000000..8a666e3e6c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java @@ -0,0 +1,15 @@ +package com.baeldung.partialupdate.util; + +import org.mapstruct.BeanMapping; +import org.mapstruct.Mapper; +import org.mapstruct.MappingTarget; +import org.mapstruct.NullValuePropertyMappingStrategy; + +import com.baeldung.partialupdate.model.Customer; +import com.baeldung.partialupdate.model.CustomerDto; + +@Mapper(componentModel = "spring") +public interface CustomerMapper { + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateCustomerFromDto(CustomerDto dto, @MappingTarget Customer entity); +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-enterprise/src/main/resources/application.properties new file mode 100644 index 0000000000..29326c6061 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/resources/application.properties @@ -0,0 +1,16 @@ + +spring.datasource.url=jdbc:h2:mem:baeldung + +# JPA-Schema-Generation +# Use below configuration to generate database schema create commands based on the entity models +# and export them into the create.sql file +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata +#spring.jpa.properties.hibernate.format_sql=true + +spring.jpa.show-sql=true +spring.main.allow-bean-definition-overriding=true + +#hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.properties.hibernate.id.new_generator_mappings=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db-boot.properties b/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db-boot.properties new file mode 100644 index 0000000000..ffca79b3f5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db-boot.properties @@ -0,0 +1,11 @@ +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false + +spring.datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +spring.datasource.username=sa +spring.datasource.password=sa + +spring.second-datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS +spring.second-datasource.username=sa +spring.second-datasource.password=sa diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db.properties new file mode 100644 index 0000000000..75534e8a54 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/main/resources/persistence-multiple-db.properties @@ -0,0 +1,13 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS +product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=false +hibernate.hbm2ddl.auto=create-drop +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..eaccf4acba --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java new file mode 100644 index 0000000000..f3697bf39f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java @@ -0,0 +1,25 @@ +package com.baeldung; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; +import com.baeldung.boot.config.PersistenceConfiguration; +import com.baeldung.multipledb.PersistenceProductConfiguration; +import com.baeldung.multipledb.PersistenceUserConfiguration; + +@RunWith(SpringRunner.class) +@DataJpaTest(excludeAutoConfiguration = { + PersistenceConfiguration.class, + PersistenceUserConfiguration.class, + PersistenceProductConfiguration.class }) +@ContextConfiguration(classes = Application.class) +public class SpringJpaContextIntegrationTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java new file mode 100644 index 0000000000..b2581b8034 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java @@ -0,0 +1,545 @@ +package com.baeldung.boot.daos; + +import org.junit.After; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; +import org.springframework.data.mapping.PropertyReferenceException; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.boot.daos.user.UserRepository; +import com.baeldung.boot.domain.User; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import java.time.LocalDate; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.*; + +public class UserRepositoryCommon { + + final String USER_EMAIL = "email@example.com"; + final String USER_EMAIL2 = "email2@example.com"; + final String USER_EMAIL3 = "email3@example.com"; + final String USER_EMAIL4 = "email4@example.com"; + final Integer INACTIVE_STATUS = 0; + final Integer ACTIVE_STATUS = 1; + final String USER_EMAIL5 = "email5@example.com"; + final String USER_EMAIL6 = "email6@example.com"; + final String USER_NAME_ADAM = "Adam"; + final String USER_NAME_PETER = "Peter"; + + @Autowired + protected UserRepository userRepository; + @Autowired + private EntityManager entityManager; + + @Test + @Transactional + public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("SAMPLE"); + user4.setEmail(USER_EMAIL4); + userRepository.save(user4); + + try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { + assertThat(foundUsersStream.count()).isEqualTo(3l); + } + } + + @Test + public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsers(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + user1.setStatus(ACTIVE_STATUS); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + user3.setStatus(INACTIVE_STATUS); + userRepository.save(user3); + + Collection allActiveUsers = userRepository.findAllActiveUsersNative(); + + assertThat(allActiveUsers.size()).isEqualTo(2); + } + + @Test + public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + user2.setStatus(ACTIVE_STATUS); + userRepository.save(user2); + + User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLike("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { + User user = new User(); + user.setName(USER_NAME_ADAM); + user.setEmail(USER_EMAIL); + user.setStatus(ACTIVE_STATUS); + userRepository.save(user); + + User userByStatus = userRepository.findUserByNameLikeNative("Ad"); + + assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); + + assertThat(usersSortByName.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test(expected = PropertyReferenceException.class) + public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); + + List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAllUsers(Sort.by("name")); + + List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); + + assertThat(usersSortByNameLength.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); + + Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); + + assertThat(usersPage.getContent() + .get(0) + .getName()).isEqualTo("SAMPLE1"); + } + + @Test + public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); + + Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); + + assertThat(usersSortByNameLength.getContent() + .get(0) + .getName()).isEqualTo(USER_NAME_PETER); + } + + @Test + @Transactional + public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + + int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + @Test + public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { + + User user1 = new User(); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + Set emails = new HashSet<>(); + emails.add(USER_EMAIL2); + emails.add(USER_EMAIL3); + + Collection usersWithEmails = userRepository.findUserByEmails(emails); + + assertThat(usersWithEmails.size()).isEqualTo(2); + } + + @Test + public void givenUsersInDBWhenFindByNameListReturnCollection() { + + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_PETER); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); + + List usersWithNames = userRepository.findUserByNameList(names); + + assertThat(usersWithNames.size()).isEqualTo(2); + } + + + @Test + @Transactional + public void whenInsertedWithQuery_ThenUserIsPersisted() { + userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true); + userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true); + + User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM); + User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER); + + assertThat(userAdam).isNotNull(); + assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL); + assertThat(userPeter).isNotNull(); + assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2); + } + + + @Test + @Transactional + public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + try (Stream users = userRepository.findAllByName("usr01")) { + assertTrue(users.allMatch(usr -> usr.equals(usr01))); + } + } + + @Test + @Transactional + public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + try (Stream users = userRepository.findAllByName("usr00")) { + assertEquals(0, users.count()); + } + } + + @Test + public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + List users = userRepository.findUsersWithGmailAddress(); + assertEquals(1, users.size()); + assertEquals(usr02, users.get(0)); + } + + @Test + @Transactional + public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); + + List users = userRepository.findAll(); + + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + } + + @Test + public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + List> predicates = new ArrayList<>(); + predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); + predicates.add(usr -> usr.getEmail().endsWith(".com")); + + List users = userRepository.findAllUsersByPredicates(predicates); + + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + } + + @Test + @Transactional + public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); + + List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); + assertTrue(users.get(0).isActive()); + assertFalse(users.get(1).isActive()); + } + + @Test + @Transactional + public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + int deletedUsersCount = userRepository.deleteDeactivatedUsers(); + + List users = userRepository.findAll(); + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + assertEquals(1, deletedUsersCount); + } + + @Test + @Transactional + public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.addDeletedColumn(); + + Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); + assertEquals(0, nativeQuery.getResultList().get(0)); + } + + @After + public void cleanUp() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..1b1d264574 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.boot.daos; + +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.User; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@DirtiesContext +public class UserRepositoryIntegrationTest extends UserRepositoryCommon { + + @Test + @Transactional + public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java new file mode 100644 index 0000000000..99eabc8271 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java @@ -0,0 +1,43 @@ +package com.baeldung.boot.daos; + +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.User; +import com.baeldung.util.BaeldungPostgresqlContainer; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.containers.PostgreSQLContainer; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Created by adam. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@ActiveProfiles({"tc", "tc-auto"}) +public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { + + @ClassRule + public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); + + @Test + @Transactional + public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java new file mode 100644 index 0000000000..be8843c166 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java @@ -0,0 +1,58 @@ +package com.baeldung.boot.daos; + +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.User; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.util.TestPropertyValues; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; +import org.testcontainers.containers.PostgreSQLContainer; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +@ActiveProfiles("tc") +@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) +public class UserRepositoryTCLiveTest extends UserRepositoryCommon { + + @ClassRule + public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") + .withDatabaseName("integration-tests-db") + .withUsername("sa") + .withPassword("sa"); + + @Test + @Transactional + public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() { + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); + userRepository.flush(); + + int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); + + assertThat(updatedUsersSize).isEqualTo(2); + } + + static class Initializer + implements ApplicationContextInitializer { + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + TestPropertyValues.of( + "spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(), + "spring.datasource.username=" + postgreSQLContainer.getUsername(), + "spring.datasource.password=" + postgreSQLContainer.getPassword() + ).applyTo(configurableApplicationContext.getEnvironment()); + } + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..bf0c85fca6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java @@ -0,0 +1,252 @@ +package com.baeldung.boot.services; + +import com.baeldung.boot.domain.Foo; +import com.baeldung.boot.services.IOperations; +import com.baeldung.util.IDUtil; +import org.hamcrest.Matchers; +import org.junit.Ignore; +import org.junit.Test; +import org.springframework.dao.DataAccessException; + +import java.io.Serializable; +import java.util.List; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.*; + +public abstract class AbstractServicePersistenceIntegrationTest { + + // tests + + // find - one + + @Test + /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { + // When + final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); + + // Then + assertNull(createdResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { + final Foo existingResource = persistNewEntity(); + getApi().findOne(existingResource.getId()); + } + + @Test + public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { + getApi().findOne(IDUtil.randomPositiveLong()); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertNotNull(retrievedResource); + } + + @Test + public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { + final Foo existingResource = persistNewEntity(); + final Foo retrievedResource = getApi().findOne(existingResource.getId()); + assertEquals(existingResource, retrievedResource); + } + + // find - one - by name + + // find - all + + @Test + /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { + getApi().findAll(); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { + final List resources = getApi().findAll(); + + assertNotNull(resources); + } + + @Test + /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + assertThat(allResources, not(Matchers. empty())); + } + + @Test + /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { + final Foo existingResource = persistNewEntity(); + + final List resources = getApi().findAll(); + + assertThat(resources, hasItem(existingResource)); + } + + @Test + /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { + persistNewEntity(); + + // When + final List allResources = getApi().findAll(); + + // Then + for (final Foo resource : allResources) { + assertNotNull(resource.getId()); + } + } + + // create + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsCreated_thenException() { + getApi().create(null); + } + + @Test + /**/public void whenResourceIsCreated_thenNoExceptions() { + persistNewEntity(); + } + + @Test + /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { + final Foo existingResource = persistNewEntity(); + + assertNotNull(getApi().findOne(existingResource.getId())); + } + + @Test + /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { + final Foo originalResource = createNewEntity(); + final Foo savedResource = getApi().create(originalResource); + + assertEquals(originalResource, savedResource); + } + + @Test(expected = RuntimeException.class) + public void whenResourceWithFailedConstraintsIsCreated_thenException() { + final Foo invalidResource = createNewEntity(); + invalidate(invalidResource); + + getApi().create(invalidResource); + } + + /** + * -- specific to the persistence engine + */ + @Test(expected = DataAccessException.class) + @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") + public void whenResourceWithIdIsCreated_thenDataAccessException() { + final Foo resourceWithId = createNewEntity(); + resourceWithId.setId(IDUtil.randomPositiveLong()); + + getApi().create(resourceWithId); + } + + // update + + @Test(expected = RuntimeException.class) + /**/public void whenNullResourceIsUpdated_thenException() { + getApi().update(null); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + getApi().update(existingResource); + } + + /** + * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException + */ + @Test(expected = RuntimeException.class) + public void whenResourceIsUpdatedWithFailedConstraints_thenException() { + final Foo existingResource = persistNewEntity(); + invalidate(existingResource); + + getApi().update(existingResource); + } + + @Test + /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { + // Given + final Foo existingResource = persistNewEntity(); + + // When + change(existingResource); + getApi().update(existingResource); + + final Foo updatedResource = getApi().findOne(existingResource.getId()); + + // Then + assertEquals(existingResource, updatedResource); + } + + // delete + + // @Test(expected = RuntimeException.class) + // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { + // // When + // getApi().delete(IDUtil.randomPositiveLong()); + // } + // + // @Test(expected = RuntimeException.class) + // public void whenResourceIsDeletedByNegativeId_thenException() { + // // When + // getApi().delete(IDUtil.randomNegativeLong()); + // } + // + // @Test + // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // } + // + // @Test + // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { + // // Given + // final Foo existingResource = persistNewEntity(); + // + // // When + // getApi().delete(existingResource.getId()); + // + // // Then + // assertNull(getApi().findOne(existingResource.getId())); + // } + + // template method + + protected Foo createNewEntity() { + return new Foo(randomAlphabetic(6)); + } + + protected abstract IOperations getApi(); + + private final void invalidate(final Foo entity) { + entity.setName(null); + } + + private final void change(final Foo entity) { + entity.setName(randomAlphabetic(6)); + } + + protected Foo persistNewEntity() { + return getApi().create(createNewEntity()); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java new file mode 100644 index 0000000000..72de4918a2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.boot.services; + +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.junit.Assert.assertNotNull; + +import org.junit.Ignore; +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.dao.InvalidDataAccessApiUsageException; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.Foo; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=Application.class) +public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { + + @Autowired + private IFooService service; + + // tests + + @Test + public final void whenContextIsBootstrapped_thenNoExceptions() { + // + } + + @Test + public final void whenEntityIsCreated_thenNoExceptions() { + service.create(new Foo(randomAlphabetic(6))); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } + + @Test(expected = DataIntegrityViolationException.class) + public final void whenEntityWithLongNameIsCreated_thenDataException() { + service.create(new Foo(randomAlphabetic(2048))); + } + + // custom Query method + + @Test + public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { + final String name = randomAlphabetic(6); + service.create(new Foo(name)); + + final Foo retrievedByName = service.retrieveByName(name); + assertNotNull(retrievedByName); + } + + // work in progress + + @Test(expected = InvalidDataAccessApiUsageException.class) + @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") + public final void whenSameEntityIsCreatedTwice_thenDataException() { + final Foo entity = new Foo(randomAlphabetic(8)); + service.create(entity); + service.create(entity); + } + + // API + + @Override + protected final IOperations getApi() { + return service; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java new file mode 100644 index 0000000000..644d1ec805 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.boot.services; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.Application; +import com.baeldung.boot.domain.Bar; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=Application.class) +public class SpringDataJPABarAuditIntegrationTest { + + private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + logger.info("setUpBeforeClass()"); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + logger.info("tearDownAfterClass()"); + } + + @Autowired + @Qualifier("barSpringDataJpaService") + private IBarService barService; + + @Autowired + private EntityManagerFactory entityManagerFactory; + + private EntityManager em; + + @Before + public void setUp() throws Exception { + logger.info("setUp()"); + em = entityManagerFactory.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown()"); + em.close(); + } + + @Test + @WithMockUser(username = "tutorialuser") + public final void whenBarsModified_thenBarsAudited() { + Bar bar = new Bar("BAR1"); + barService.create(bar); + assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + bar.setName("BAR2"); + bar = barService.update(bar); + assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); + assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java new file mode 100644 index 0000000000..306798aa68 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.elementcollection; + +import com.baeldung.elementcollection.model.Employee; +import com.baeldung.elementcollection.model.Phone; +import com.baeldung.elementcollection.repository.EmployeeRepository; +import org.junit.After; +import org.junit.Before; +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 org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = ElementCollectionApplication.class) +public class ElementCollectionIntegrationTest { + + @Autowired + private EmployeeRepository employeeRepository; + + @Before + public void init() { + Employee employee = new Employee(1, "Fred"); + employee.setPhones( + Arrays.asList(new Phone("work", "+55", "99999-9999"), new Phone("home", "+55", "98888-8888"))); + employeeRepository.save(employee); + } + + @After + public void clean() { + employeeRepository.remove(1); + } + + @Test(expected = org.hibernate.LazyInitializationException.class) + public void whenAccessLazyCollection_thenThrowLazyInitializationException() { + Employee employee = employeeRepository.findById(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + public void whenUseJPAQL_thenFetchResult() { + Employee employee = employeeRepository.findByJPQL(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + public void whenUseEntityGraph_thenFetchResult() { + Employee employee = employeeRepository.findByEntityGraph(1); + assertThat(employee.getPhones().size(), is(2)); + } + + @Test + @Transactional + public void whenUseTransaction_thenFetchResult() { + Employee employee = employeeRepository.findById(1); + assertThat(employee.getPhones().size(), is(2)); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java new file mode 100644 index 0000000000..a1f4a3fa2c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.multipledb; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Collections; +import java.util.Optional; + +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; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.multipledb.dao.product.ProductRepository; +import com.baeldung.multipledb.dao.user.PossessionRepository; +import com.baeldung.multipledb.dao.user.UserRepository; +import com.baeldung.multipledb.model.product.Product; +import com.baeldung.multipledb.model.user.PossessionMultipleDB; +import com.baeldung.multipledb.model.user.UserMultipleDB; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=MultipleDbApplication.class) +@EnableTransactionManagement +public class JpaMultipleDBIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Autowired + private PossessionRepository possessionRepository; + + @Autowired + private ProductRepository productRepository; + + // tests + + @Test + @Transactional("userTransactionManager") + public void whenCreatingUser_thenCreated() { + UserMultipleDB user = new UserMultipleDB(); + user.setName("John"); + user.setEmail("john@test.com"); + user.setAge(20); + PossessionMultipleDB p = new PossessionMultipleDB("sample"); + p = possessionRepository.save(p); + user.setPossessionList(Collections.singletonList(p)); + user = userRepository.save(user); + final Optional result = userRepository.findById(user.getId()); + assertTrue(result.isPresent()); + System.out.println(result.get().getPossessionList()); + assertEquals(1, result.get().getPossessionList().size()); + } + + @Test + @Transactional("userTransactionManager") + public void whenCreatingUsersWithSameEmail_thenRollback() { + UserMultipleDB user1 = new UserMultipleDB(); + user1.setName("John"); + user1.setEmail("john@test.com"); + user1.setAge(20); + user1 = userRepository.save(user1); + assertTrue(userRepository.findById(user1.getId()).isPresent()); + + UserMultipleDB user2 = new UserMultipleDB(); + user2.setName("Tom"); + user2.setEmail("john@test.com"); + user2.setAge(10); + try { + user2 = userRepository.save(user2); + userRepository.flush(); + fail("DataIntegrityViolationException should be thrown!"); + } catch (final DataIntegrityViolationException e) { + // Expected + } catch (final Exception e) { + fail("DataIntegrityViolationException should be thrown, instead got: " + e); + } + } + + @Test + @Transactional("productTransactionManager") + public void whenCreatingProduct_thenCreated() { + Product product = new Product(); + product.setName("Book"); + product.setId(2); + product.setPrice(20); + product = productRepository.save(product); + + assertTrue(productRepository.findById(product.getId()).isPresent()); + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9bfba61a3b --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java @@ -0,0 +1,144 @@ +package com.baeldung.multipledb; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.junit.Before; +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.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.multipledb.PersistenceProductConfiguration; +import com.baeldung.multipledb.dao.product.ProductRepository; +import com.baeldung.multipledb.model.product.Product; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=MultipleDbApplication.class) +@EnableTransactionManagement +public class ProductRepositoryIntegrationTest { + + @Autowired + private ProductRepository productRepository; + + @Before + @Transactional("productTransactionManager") + public void setUp() { + productRepository.save(Product.from(1001, "Book", 21)); + productRepository.save(Product.from(1002, "Coffee", 10)); + productRepository.save(Product.from(1003, "Jeans", 30)); + productRepository.save(Product.from(1004, "Shirt", 32)); + productRepository.save(Product.from(1005, "Bacon", 10)); + } + + @Test + public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1001, 1002) + .contains(id))); + } + + @Test + public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { + Pageable pageRequest = PageRequest.of(1, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1003, 1004) + .contains(id))); + } + + @Test + public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { + Pageable pageRequest = PageRequest.of(2, 2); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(1)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1005) + .contains(id))); + } + + @Test + public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); + + } + + @Test + public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") + .descending()); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(3)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); + + } + + @Test + public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { + Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") + .descending() + .and(Sort.by("name"))); + + Page result = productRepository.findAll(pageRequest); + + assertThat(result.getContent(), hasSize(5)); + assertThat(result.getContent() + .stream() + .map(Product::getId) + .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); + + } + + @Test + public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { + Pageable pageRequest = PageRequest.of(0, 2); + + List result = productRepository.findAllByPrice(10, pageRequest); + + assertThat(result, hasSize(2)); + assertTrue(result.stream() + .map(Product::getId) + .allMatch(id -> Arrays.asList(1002, 1005) + .contains(id))); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..71a4dbda3f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy.properties") +class QuotedLowerCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..6b1c984600 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") +class QuotedLowerCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..f819327a5c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy.properties") +class QuotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..bd23b81b4b --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,81 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") +class QuotedUpperCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..1850fea173 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy.properties") +class SpringPhysicalNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..e26ebb148d --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") +class SpringPhysicalNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..6311c42e93 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,86 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy.properties") +class UnquotedLowerCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..033a213cf5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") +class UnquotedLowerCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java new file mode 100644 index 0000000000..7af8001854 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy.properties") +class UnquotedUpperCaseNamingStrategyH2IntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Expected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java new file mode 100644 index 0000000000..0151e7ece4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -0,0 +1,85 @@ +package com.baeldung.namingstrategy; + +import org.hibernate.exception.SQLGrammarException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.TestPropertySource; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) +@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") +class UnquotedUpperCaseNamingStrategyPostgresLiveTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private PersonRepository personRepository; + + @BeforeEach + void insertPeople() { + personRepository.saveAll(Arrays.asList( + new Person(1L, "John", "Doe"), + new Person(2L, "Jane", "Doe"), + new Person(3L, "Ted", "Mosby") + )); + } + + @ParameterizedTest + @ValueSource(strings = {"person", "PERSON", "Person"}) + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { + Query query = entityManager.createNativeQuery("select * from " + tableName); + + // Expected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { + Query query = entityManager.createNativeQuery("select * from \"PERSON\""); + + // Unexpected result + assertThrows(SQLGrammarException.class, query::getResultStream); + } + + @Test + void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { + Query query = entityManager.createNativeQuery("select * from \"person\""); + + // Unexpected result + List result = (List) query.getResultStream() + .map(this::fromDatabase) + .collect(Collectors.toList()); + + assertThat(result).isNotEmpty(); + } + + public Person fromDatabase(Object databaseRow) { + Object[] typedDatabaseRow = (Object[]) databaseRow; + + return new Person( + ((BigInteger) typedDatabaseRow[0]).longValue(), + (String) typedDatabaseRow[1], + (String) typedDatabaseRow[2] + ); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..350b67e1c9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java @@ -0,0 +1,56 @@ +package com.baeldung.osiv; + +import com.baeldung.osiv.model.BasicUser; +import com.baeldung.osiv.repository.BasicUserRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Arrays; +import java.util.HashSet; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest +@AutoConfigureMockMvc +@ActiveProfiles("test") +@ContextConfiguration(classes = OsivApplication.class) +class UserControllerIntegrationTest { + + @Autowired + private BasicUserRepository userRepository; + + @Autowired + private MockMvc mockMvc; + + @BeforeEach + void setUp() { + BasicUser user = new BasicUser(); + user.setUsername("root"); + user.setPermissions(new HashSet<>(Arrays.asList("PERM_READ", "PERM_WRITE"))); + + userRepository.save(user); + } + + @Test + void givenTheUserExists_WhenOsivIsEnabled_ThenLazyInitWorkEverywhere() throws Exception { + mockMvc.perform(get("/users/root")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.username").value("root")) + .andExpect(jsonPath("$.permissions", containsInAnyOrder("PERM_READ", "PERM_WRITE"))); + } + + @AfterEach + void flushDb() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java new file mode 100644 index 0000000000..874e18c4ad --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.partialupdate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +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 com.baeldung.partialupdate.model.Customer; +import com.baeldung.partialupdate.model.CustomerDto; +import com.baeldung.partialupdate.model.CustomerStructured; +import com.baeldung.partialupdate.service.CustomerService; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = PartialUpdateApplication.class) +public class PartialUpdateUnitTest { + + @Autowired + CustomerService service; + + @Test + public void givenCustomer_whenUpdate_thenSuccess() { + Customer myCustomer = service.addCustomer("John"); + myCustomer = service.updateCustomer(myCustomer.id, "+00"); + assertEquals("+00", myCustomer.phone); + } + + @Test + public void givenCustomer_whenUpdateWithQuery_thenSuccess() { + Customer myCustomer = service.addCustomer("John"); + service.updateCustomerWithCustomQuery(myCustomer.id, "+88"); + myCustomer = service.getCustomer(myCustomer.id); + assertEquals("+88", myCustomer.phone); + } + + @Test + public void givenCustomerDto_whenUpdateWithMapper_thenSuccess() { + CustomerDto dto = new CustomerDto(new Customer()); + dto.name = "Johnny"; + Customer entity = service.addCustomer(dto); + + CustomerDto dto2 = new CustomerDto(entity.id); + dto2.phone = "+44"; + entity = service.updateCustomer(dto2); + + assertEquals("Johnny", entity.name); + } + + @Test + public void givenCustomerStructured_whenUpdateCustomerPhone_thenSuccess() { + CustomerStructured myCustomer = service.addCustomerStructured("John"); + assertEquals(null, myCustomer.contactPhones); + + service.addCustomerPhone(myCustomer.id, "+44"); + myCustomer = service.updateCustomerStructured(myCustomer.id, "Mr. John"); + + assertNotEquals(null, myCustomer.contactPhones); + assertEquals(1, myCustomer.contactPhones.size()); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java new file mode 100644 index 0000000000..e5ad2dd448 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java @@ -0,0 +1,35 @@ +package com.baeldung.util; + +import org.testcontainers.containers.PostgreSQLContainer; + +public class BaeldungPostgresqlContainer extends PostgreSQLContainer { + + private static final String IMAGE_VERSION = "postgres:11.1"; + + private static BaeldungPostgresqlContainer container; + + + private BaeldungPostgresqlContainer() { + super(IMAGE_VERSION); + } + + public static BaeldungPostgresqlContainer getInstance() { + if (container == null) { + container = new BaeldungPostgresqlContainer(); + } + return container; + } + + @Override + public void start() { + super.start(); + System.setProperty("DB_URL", container.getJdbcUrl()); + System.setProperty("DB_USERNAME", container.getUsername()); + System.setProperty("DB_PASSWORD", container.getPassword()); + } + + @Override + public void stop() { + //do nothing, JVM handles shut down + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/IDUtil.java b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/IDUtil.java new file mode 100644 index 0000000000..45e72e046d --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/util/IDUtil.java @@ -0,0 +1,33 @@ +package com.baeldung.util; + +import java.util.Random; + +public final class IDUtil { + + private IDUtil() { + throw new AssertionError(); + } + + // API + + public static String randomPositiveLongAsString() { + return Long.toString(randomPositiveLong()); + } + + public static String randomNegativeLongAsString() { + return Long.toString(randomNegativeLong()); + } + + public static long randomPositiveLong() { + long id = new Random().nextLong() * 10000; + id = (id < 0) ? (-1 * id) : id; + return id; + } + + private static long randomNegativeLong() { + long id = new Random().nextLong() * 10000; + id = (id > 0) ? (-1 * id) : id; + return id; + } + +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/application-test.properties new file mode 100644 index 0000000000..e3d39fe1e2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/application-test.properties @@ -0,0 +1,3 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:h2:mem:baeldung + diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..04b29de41f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..6643c12c8a --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..36898d5b4f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..6d56d58749 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..706b12b1b6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties new file mode 100644 index 0000000000..c9a0c6f24c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:spring-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..b22472bd8f --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties new file mode 100644 index 0000000000..8083515b4b --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties new file mode 100644 index 0000000000..da03a0d7b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy +spring.datasource.username=postgres +spring.datasource.password=root + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties new file mode 100644 index 0000000000..d1b63e008c --- /dev/null +++ b/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties @@ -0,0 +1,9 @@ +spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy +spring.datasource.username=sa +spring.datasource.password= + +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy +#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata +#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file From 7a86d7de495ebc36a6fae9be9d1ad9c5e888eb4a Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:30:43 +0530 Subject: [PATCH 054/155] JAVA-66: New module spring-data-jpa-filtering --- .../spring-data-jpa-filtering/README.md | 19 +++++ .../spring-data-jpa-filtering/pom.xml | 77 +++++++++++++++++ .../main/java/com/baeldung/Application.java | 13 +++ .../com/baeldung/config/StudentJpaConfig.java | 68 +++++++++++++++ .../java/com/baeldung/entity/Customer.java | 37 ++++++++ .../dao/ManyStudentRepository.java | 10 +++ .../persistence/dao/ManyTagRepository.java | 7 ++ .../persistence/dao/StudentRepository.java | 24 ++++++ .../inmemory/persistence/model/KVTag.java | 34 ++++++++ .../persistence/model/LocationTag.java | 40 +++++++++ .../persistence/model/ManyStudent.java | 33 ++++++++ .../inmemory/persistence/model/ManyTag.java | 40 +++++++++ .../inmemory/persistence/model/SkillTag.java | 30 +++++++ .../inmemory/persistence/model/Student.java | 74 ++++++++++++++++ .../baeldung/projection/model/Address.java | 57 +++++++++++++ .../com/baeldung/projection/model/Person.java | 47 +++++++++++ .../repository/AddressRepository.java | 11 +++ .../repository/PersonRepository.java | 14 ++++ .../baeldung/projection/view/AddressView.java | 7 ++ .../baeldung/projection/view/PersonDto.java | 34 ++++++++ .../baeldung/projection/view/PersonView.java | 12 +++ .../repository/CustomerRepository.java | 19 +++++ .../resources/persistence-student.properties | 11 +++ .../AdvancedTaggingIntegrationTest.java | 83 ++++++++++++++++++ .../repository/InMemoryDBIntegrationTest.java | 84 +++++++++++++++++++ .../JpaProjectionIntegrationTest.java | 63 ++++++++++++++ .../CustomerRepositoryIntegrationTest.java | 64 ++++++++++++++ .../resources/persistence-student.properties | 9 ++ .../resources/projection-clean-up-data.sql | 2 + .../test/resources/projection-insert-data.sql | 2 + 30 files changed, 1025 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-filtering/README.md create mode 100644 persistence-modules/spring-data-jpa-filtering/pom.xml create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/config/StudentJpaConfig.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/Student.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/main/resources/persistence-student.properties create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/InMemoryDBIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/resources/persistence-student.properties create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-clean-up-data.sql create mode 100644 persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-insert-data.sql diff --git a/persistence-modules/spring-data-jpa-filtering/README.md b/persistence-modules/spring-data-jpa-filtering/README.md new file mode 100644 index 0000000000..fe2f181154 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/README.md @@ -0,0 +1,19 @@ +## Spring Data JPA - Filtering + +This module contains articles about filtering data using Spring Data JPA + +### Relevant Articles: +- [An Advanced Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging-advanced) +- [A Simple Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging) +- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) +- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator + diff --git a/persistence-modules/spring-data-jpa-filtering/pom.xml b/persistence-modules/spring-data-jpa-filtering/pom.xml new file mode 100644 index 0000000000..2039ef1a37 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + spring-data-jpa-filtering + spring-data-jpa-filtering + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.hibernate + hibernate-ehcache + + + org.hibernate + hibernate-envers + + + + com.h2database + h2 + + + + + org.testcontainers + postgresql + ${testcontainers.postgresql.version} + test + + + + org.postgresql + postgresql + + + + + org.springframework.security + spring-security-test + test + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + + com.google.guava + guava + ${guava.version} + + + + + com.baeldung.boot.Application + 1.10.6 + 42.2.5 + 21.0 + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..3ea3d113da --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/config/StudentJpaConfig.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/config/StudentJpaConfig.java new file mode 100644 index 0000000000..08f37ea806 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/config/StudentJpaConfig.java @@ -0,0 +1,68 @@ +package com.baeldung.config; + +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableJpaRepositories(basePackages = "com.baeldung.inmemory.persistence.dao") +@PropertySource("persistence-student.properties") +@EnableTransactionManagement +public class StudentJpaConfig { + + @Autowired + private Environment env; + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); + dataSource.setUrl(env.getProperty("jdbc.url")); + dataSource.setUsername(env.getProperty("jdbc.user")); + dataSource.setPassword(env.getProperty("jdbc.pass")); + + return dataSource; + } + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan(new String[] { "com.baeldung.inmemory.persistence.model" }); + em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); + em.setJpaProperties(additionalProperties()); + return em; + } + + @Bean + JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory); + return transactionManager; + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); + hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", env.getProperty("hibernate.cache.use_second_level_cache")); + hibernateProperties.setProperty("hibernate.cache.use_query_cache", env.getProperty("hibernate.cache.use_query_cache")); + + return hibernateProperties; + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java new file mode 100644 index 0000000000..efcae73853 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java @@ -0,0 +1,37 @@ +package com.baeldung.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Customer { + + @Id + @GeneratedValue + private long id; + private String name; + private String email; + + public Customer(String name, String email) { + this.name = name; + this.email = email; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java new file mode 100644 index 0000000000..a2aa0c5780 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyStudentRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.inmemory.persistence.dao; + +import com.baeldung.inmemory.persistence.model.ManyStudent; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface ManyStudentRepository extends JpaRepository { + List findByManyTags_Name(String name); +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java new file mode 100644 index 0000000000..63337f3cb9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/ManyTagRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.inmemory.persistence.dao; + +import com.baeldung.inmemory.persistence.model.ManyTag; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ManyTagRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java new file mode 100644 index 0000000000..8ac91fbf0c --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/dao/StudentRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.inmemory.persistence.dao; + +import com.baeldung.inmemory.persistence.model.Student; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface StudentRepository extends JpaRepository { + + @Query("SELECT s FROM Student s JOIN s.tags t WHERE t = LOWER(:tag)") + List retrieveByTag(@Param("tag") String tag); + + @Query("SELECT s FROM Student s JOIN s.tags t WHERE s.name = LOWER(:name) AND t = LOWER(:tag)") + List retrieveByNameFilterByTag(@Param("name") String name, @Param("tag") String tag); + + @Query("SELECT s FROM Student s JOIN s.skillTags t WHERE t.name = LOWER(:tagName) AND t.value > :tagValue") + List retrieveByNameFilterByMinimumSkillTag(@Param("tagName") String tagName, @Param("tagValue") int tagValue); + + @Query("SELECT s FROM Student s JOIN s.kvTags t WHERE t.key = LOWER(:key)") + List retrieveByKeyTag(@Param("key") String key); + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java new file mode 100644 index 0000000000..1fc186f4ce --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/KVTag.java @@ -0,0 +1,34 @@ +package com.baeldung.inmemory.persistence.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class KVTag { + private String key; + private String value; + + public KVTag() { + } + + public KVTag(String key, String value) { + super(); + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java new file mode 100644 index 0000000000..b12ad9fbd1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/LocationTag.java @@ -0,0 +1,40 @@ +package com.baeldung.inmemory.persistence.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class LocationTag { + private String name; + private int xPos; + private int yPos; + + public LocationTag() { + } + + public LocationTag(String name, int xPos, int yPos) { + super(); + this.name = name; + this.xPos = xPos; + this.yPos = yPos; + } + + public String getName() { + return name; + } + + public int getxPos() { + return xPos; + } + + public void setxPos(int xPos) { + this.xPos = xPos; + } + + public int getyPos() { + return yPos; + } + + public void setyPos(int yPos) { + this.yPos = yPos; + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java new file mode 100644 index 0000000000..190740d582 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyStudent.java @@ -0,0 +1,33 @@ +package com.baeldung.inmemory.persistence.model; + +import javax.persistence.*; +import java.util.HashSet; +import java.util.Set; + +@Entity +public class ManyStudent { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String name; + + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable(name = "manystudent_manytags", joinColumns = @JoinColumn(name = "manystudent_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "manytag_id", referencedColumnName = "id")) + private Set manyTags = new HashSet<>(); + + public ManyStudent() { + } + + public ManyStudent(String name) { + this.name = name; + } + + public Set getManyTags() { + return manyTags; + } + + public void setManyTags(Set manyTags) { + this.manyTags.addAll(manyTags); + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java new file mode 100644 index 0000000000..5af898f7df --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/ManyTag.java @@ -0,0 +1,40 @@ +package com.baeldung.inmemory.persistence.model; + +import javax.persistence.*; +import java.util.HashSet; +import java.util.Set; + +@Entity +public class ManyTag { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + private String name; + + @ManyToMany(mappedBy = "manyTags") + private Set students = new HashSet<>(); + + public ManyTag() { + } + + public ManyTag(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getStudents() { + return students; + } + + public void setStudents(Set students) { + this.students.addAll(students); + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java new file mode 100644 index 0000000000..738b5d0b36 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/SkillTag.java @@ -0,0 +1,30 @@ +package com.baeldung.inmemory.persistence.model; + +import javax.persistence.Embeddable; + +@Embeddable +public class SkillTag { + private String name; + private int value; + + public SkillTag() { + } + + public SkillTag(String name, int value) { + super(); + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/Student.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/Student.java new file mode 100644 index 0000000000..f0e824e165 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/inmemory/persistence/model/Student.java @@ -0,0 +1,74 @@ +package com.baeldung.inmemory.persistence.model; + +import java.util.ArrayList; +import java.util.List; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Student { + + @Id + private long id; + private String name; + + @ElementCollection + private List tags = new ArrayList<>(); + + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + + public Student() { + } + + public Student(long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java new file mode 100644 index 0000000000..0c5a3eac60 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java @@ -0,0 +1,57 @@ +package com.baeldung.projection.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Address { + @Id + private Long id; + @OneToOne + private Person person; + private String state; + private String city; + private String street; + private String zipCode; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java new file mode 100644 index 0000000000..d18bd1c72d --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java @@ -0,0 +1,47 @@ +package com.baeldung.projection.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Person { + @Id + private Long id; + private String firstName; + private String lastName; + @OneToOne(mappedBy = "person") + private Address address; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java new file mode 100644 index 0000000000..c1053f4867 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.projection.repository; + +import com.baeldung.projection.view.AddressView; +import com.baeldung.projection.model.Address; +import org.springframework.data.repository.Repository; + +import java.util.List; + +public interface AddressRepository extends Repository { + List getAddressByState(String state); +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java new file mode 100644 index 0000000000..64bc7471e6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.projection.repository; + +import com.baeldung.projection.model.Person; +import com.baeldung.projection.view.PersonDto; +import com.baeldung.projection.view.PersonView; +import org.springframework.data.repository.Repository; + +public interface PersonRepository extends Repository { + PersonView findByLastName(String lastName); + + PersonDto findByFirstName(String firstName); + + T findByLastName(String lastName, Class type); +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java new file mode 100644 index 0000000000..7a24a1e9b9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java @@ -0,0 +1,7 @@ +package com.baeldung.projection.view; + +public interface AddressView { + String getZipCode(); + + PersonView getPerson(); +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java new file mode 100644 index 0000000000..1fd924450b --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java @@ -0,0 +1,34 @@ +package com.baeldung.projection.view; + +import java.util.Objects; + +public class PersonDto { + private final String firstName; + private final String lastName; + + public PersonDto(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PersonDto personDto = (PersonDto) o; + return Objects.equals(firstName, personDto.firstName) && Objects.equals(lastName, personDto.lastName); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java new file mode 100644 index 0000000000..36777ec26f --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java @@ -0,0 +1,12 @@ +package com.baeldung.projection.view; + +import org.springframework.beans.factory.annotation.Value; + +public interface PersonView { + String getFirstName(); + + String getLastName(); + + @Value("#{target.firstName + ' ' + target.lastName}") + String getFullName(); +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java new file mode 100644 index 0000000000..65b22bbd84 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.repository; + +import com.baeldung.entity.Customer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface CustomerRepository extends JpaRepository { + + List findByName(String name); + + List findByNameAndEmail(String name, String email); + + @Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)") + List findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email); + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/resources/persistence-student.properties b/persistence-modules/spring-data-jpa-filtering/src/main/resources/persistence-student.properties new file mode 100644 index 0000000000..d4c82420de --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/resources/persistence-student.properties @@ -0,0 +1,11 @@ +jdbc.driverClassName=com.mysql.cj.jdbc.Driver +jdbc.url=jdbc:mysql://localhost:3306/myDb +jdbc.user=tutorialuser +jdbc.pass=tutorialpass + +hibernate.dialect=org.hibernate.dialect.MySQL5Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop + +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java new file mode 100644 index 0000000000..e98c1fa4a6 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/AdvancedTaggingIntegrationTest.java @@ -0,0 +1,83 @@ +package com.baeldung.persistence.repository; + +import com.baeldung.config.StudentJpaConfig; +import com.baeldung.inmemory.persistence.dao.ManyStudentRepository; +import com.baeldung.inmemory.persistence.dao.ManyTagRepository; +import com.baeldung.inmemory.persistence.dao.StudentRepository; +import com.baeldung.inmemory.persistence.model.ManyStudent; +import com.baeldung.inmemory.persistence.model.ManyTag; +import com.baeldung.inmemory.persistence.model.SkillTag; +import com.baeldung.inmemory.persistence.model.Student; +import com.baeldung.inmemory.persistence.model.KVTag; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) +@Transactional +@DirtiesContext +public class AdvancedTaggingIntegrationTest { + @Resource + private StudentRepository studentRepository; + + @Resource + private ManyStudentRepository manyStudentRepository; + + @Resource + private ManyTagRepository manyTagRepository; + + @Test + public void givenStudentWithSkillTags_whenSave_thenGetByNameAndSkillTag() { + Student student = new Student(1, "Will"); + SkillTag skill1 = new SkillTag("java", 5); + student.setSkillTags(Arrays.asList(skill1)); + studentRepository.save(student); + + Student student2 = new Student(2, "Joe"); + SkillTag skill2 = new SkillTag("java", 1); + student2.setSkillTags(Arrays.asList(skill2)); + studentRepository.save(student2); + + List students = studentRepository.retrieveByNameFilterByMinimumSkillTag("java", 3); + assertEquals("size incorrect", 1, students.size()); + } + + @Test + public void givenStudentWithKVTags_whenSave_thenGetByTagOk() { + Student student = new Student(0, "John"); + student.setKVTags(Arrays.asList(new KVTag("department", "computer science"))); + studentRepository.save(student); + + Student student2 = new Student(1, "James"); + student2.setKVTags(Arrays.asList(new KVTag("department", "humanities"))); + studentRepository.save(student2); + + List students = studentRepository.retrieveByKeyTag("department"); + assertEquals("size incorrect", 2, students.size()); + } + + @Test + public void givenStudentWithManyTags_whenSave_theyGetByTagOk() { + ManyTag tag = new ManyTag("full time"); + manyTagRepository.save(tag); + + ManyStudent student = new ManyStudent("John"); + student.setManyTags(Collections.singleton(tag)); + manyStudentRepository.save(student); + + List students = manyStudentRepository.findByManyTags_Name("full time"); + assertEquals("size incorrect", 1, students.size()); + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/InMemoryDBIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/InMemoryDBIntegrationTest.java new file mode 100644 index 0000000000..d8d867792e --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/persistence/repository/InMemoryDBIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.persistence.repository; + +import com.baeldung.config.StudentJpaConfig; +import com.baeldung.inmemory.persistence.dao.StudentRepository; +import com.baeldung.inmemory.persistence.model.Student; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { StudentJpaConfig.class }, loader = AnnotationConfigContextLoader.class) +@Transactional +@DirtiesContext +public class InMemoryDBIntegrationTest { + + @Resource + private StudentRepository studentRepository; + + private static final long ID = 1; + private static final String NAME = "john"; + + @Test + public void givenStudent_whenSave_thenGetOk() { + Student student = new Student(ID, NAME); + studentRepository.save(student); + + Student student2 = studentRepository.findById(ID).get(); + assertEquals("name incorrect", NAME, student2.getName()); + } + + @Test + public void givenStudentWithTags_whenSave_thenGetByTagOk() { + Student student = new Student(ID, NAME); + student.setTags(Arrays.asList("full time", "computer science")); + studentRepository.save(student); + + Student student2 = studentRepository.retrieveByTag("full time").get(0); + assertEquals("name incorrect", NAME, student2.getName()); + } + + @Test + public void givenMultipleStudentsWithTags_whenSave_thenGetByTagReturnsCorrectCount() { + Student student = new Student(0, "Larry"); + student.setTags(Arrays.asList("full time", "computer science")); + studentRepository.save(student); + + Student student2 = new Student(1, "Curly"); + student2.setTags(Arrays.asList("part time", "rocket science")); + studentRepository.save(student2); + + Student student3 = new Student(2, "Moe"); + student3.setTags(Arrays.asList("full time", "philosophy")); + studentRepository.save(student3); + + Student student4 = new Student(3, "Shemp"); + student4.setTags(Arrays.asList("part time", "mathematics")); + studentRepository.save(student4); + + List students = studentRepository.retrieveByTag("full time"); + assertEquals("size incorrect", 2, students.size()); + } + + @Test + public void givenStudentWithTags_whenSave_thenGetByNameAndTagOk() { + Student student = new Student(ID, NAME); + student.setTags(Arrays.asList("full time", "computer science")); + studentRepository.save(student); + + Student student2 = studentRepository.retrieveByNameFilterByTag("John", "full time").get(0); + assertEquals("name incorrect", NAME, student2.getName()); + } + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java new file mode 100644 index 0000000000..96eaf4ed07 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java @@ -0,0 +1,63 @@ +package com.baeldung.projection; + +import com.baeldung.projection.model.Person; +import com.baeldung.projection.repository.AddressRepository; +import com.baeldung.projection.repository.PersonRepository; +import com.baeldung.projection.view.AddressView; +import com.baeldung.projection.view.PersonDto; +import com.baeldung.projection.view.PersonView; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; + +@DataJpaTest +@RunWith(SpringRunner.class) +@Sql(scripts = "/projection-insert-data.sql") +@Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD) +public class JpaProjectionIntegrationTest { + @Autowired + private AddressRepository addressRepository; + + @Autowired + private PersonRepository personRepository; + + @Test + public void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() { + AddressView addressView = addressRepository.getAddressByState("CA").get(0); + assertThat(addressView.getZipCode()).isEqualTo("90001"); + + PersonView personView = addressView.getPerson(); + assertThat(personView.getFirstName()).isEqualTo("John"); + assertThat(personView.getLastName()).isEqualTo("Doe"); + } + + @Test + public void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() { + PersonView personView = personRepository.findByLastName("Doe"); + assertThat(personView.getFullName()).isEqualTo("John Doe"); + } + + @Test + public void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() { + PersonDto personDto = personRepository.findByFirstName("John"); + assertThat(personDto.getFirstName()).isEqualTo("John"); + assertThat(personDto.getLastName()).isEqualTo("Doe"); + } + + @Test + public void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() { + Person person = personRepository.findByLastName("Doe", Person.class); + PersonView personView = personRepository.findByLastName("Doe", PersonView.class); + PersonDto personDto = personRepository.findByLastName("Doe", PersonDto.class); + + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(personView.getFirstName()).isEqualTo("John"); + assertThat(personDto.getFirstName()).isEqualTo("John"); + } +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java new file mode 100644 index 0000000000..5d6457ce30 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java @@ -0,0 +1,64 @@ +package com.baeldung.repository; + +import com.baeldung.entity.Customer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@DataJpaTest +@RunWith(SpringRunner.class) +public class CustomerRepositoryIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Autowired + private CustomerRepository repository; + + @Before + public void before() { + entityManager.persist(new Customer("A", "A@example.com")); + entityManager.persist(new Customer("D", null)); + entityManager.persist(new Customer("D", "D@example.com")); + } + + @Test + public void givenQueryMethod_whenEmailIsNull_thenFoundByNullEmail() { + List customers = repository.findByNameAndEmail("D", null); + + assertEquals(1, customers.size()); + Customer actual = customers.get(0); + + assertEquals(null, actual.getEmail()); + assertEquals("D", actual.getName()); + } + + @Test + public void givenQueryMethod_whenEmailIsAbsent_thenIgnoreEmail() { + List customers = repository.findByName("D"); + + assertEquals(2, customers.size()); + } + + @Test + public void givenQueryAnnotation_whenEmailIsNull_thenIgnoreEmail() { + List customers = repository.findCustomerByNameAndEmail("D", null); + + assertEquals(2, customers.size()); + } + + @After + public void cleanUp() { + repository.deleteAll(); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/resources/persistence-student.properties b/persistence-modules/spring-data-jpa-filtering/src/test/resources/persistence-student.properties new file mode 100644 index 0000000000..3b6b580630 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/resources/persistence-student.properties @@ -0,0 +1,9 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1 + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create + +hibernate.cache.use_second_level_cache=false +hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-clean-up-data.sql b/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-clean-up-data.sql new file mode 100644 index 0000000000..d34f6f0636 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-clean-up-data.sql @@ -0,0 +1,2 @@ +DELETE FROM address; +DELETE FROM person; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-insert-data.sql b/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-insert-data.sql new file mode 100644 index 0000000000..544dcc4b88 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-insert-data.sql @@ -0,0 +1,2 @@ +INSERT INTO person(id,first_name,last_name) VALUES (1,'John','Doe'); +INSERT INTO address(id,person_id,state,city,street,zip_code) VALUES (1,1,'CA', 'Los Angeles', 'Standford Ave', '90001'); \ No newline at end of file From 52da4c8ee8d39c0bd419d0ed2834fc13e6dac8f7 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:31:01 +0530 Subject: [PATCH 055/155] JAVA-66: New module spring-data-jpa-query --- .../spring-data-jpa-query/README.md | 22 ++ .../spring-data-jpa-query/pom.xml | 48 +++++ .../main/java/com/baeldung/Application.java | 13 ++ .../baeldung/aggregation/model/Comment.java | 85 ++++++++ .../com/baeldung/aggregation/model/Post.java | 75 +++++++ .../model/custom/CommentCount.java | 27 +++ .../model/custom/ICommentCount.java | 8 + .../repository/CommentRepository.java | 27 +++ .../baeldung/boot/daos/ArticleRepository.java | 23 +++ .../com/baeldung/boot/domain/Article.java | 23 +++ .../passenger/CustomPassengerRepository.java | 8 + .../baeldung/boot/passenger/Passenger.java | 82 ++++++++ .../boot/passenger/PassengerRepository.java | 22 ++ .../passenger/PassengerRepositoryImpl.java | 20 ++ .../entitygraph/model/Characteristic.java | 43 ++++ .../com/baeldung/entitygraph/model/Item.java | 48 +++++ .../repository/CharacteristicsRepository.java | 13 ++ .../repository/ItemRepository.java | 13 ++ .../main/java/com/baeldung/exists/Car.java | 48 +++++ .../com/baeldung/exists/CarRepository.java | 24 +++ .../com/baeldung/joins/model/Department.java | 45 +++++ .../com/baeldung/joins/model/Employee.java | 69 +++++++ .../java/com/baeldung/joins/model/Phone.java | 44 ++++ .../src/main/resources/apple-fruit-data.xml | 7 + .../resources/application-joins.properties | 1 + .../src/main/resources/application.properties | 1 + .../src/main/resources/db/import_joins.sql | 13 ++ .../src/main/resources/fruit-data.json | 14 ++ .../src/main/resources/guava-fruit-data.xml | 7 + .../src/main/resources/import_entities.sql | 3 + .../SpringDataAggregateIntegrationTest.java | 107 ++++++++++ .../ArticleRepositoryIntegrationTest.java | 67 ++++++ .../PassengerRepositoryIntegrationTest.java | 190 ++++++++++++++++++ .../EntityGraphIntegrationTest.java | 39 ++++ .../exists/CarRepositoryIntegrationTest.java | 87 ++++++++ .../joins/JpaJoinsIntegrationTest.java | 142 +++++++++++++ .../src/test/resources/entitygraph-data.sql | 7 + .../resources/projection-clean-up-data.sql | 2 + .../test/resources/projection-insert-data.sql | 2 + .../test/resources/test-aggregation-data.sql | 7 + .../src/test/resources/test-fruit-data.sql | 6 + 41 files changed, 1532 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-query/README.md create mode 100644 persistence-modules/spring-data-jpa-query/pom.xml create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/Passenger.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Characteristic.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Item.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/Car.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/CarRepository.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Department.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Employee.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Phone.java create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/apple-fruit-data.xml create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/application-joins.properties create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/db/import_joins.sql create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/fruit-data.json create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/guava-fruit-data.xml create mode 100644 persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql create mode 100644 persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-query/src/test/resources/entitygraph-data.sql create mode 100644 persistence-modules/spring-data-jpa-query/src/test/resources/projection-clean-up-data.sql create mode 100644 persistence-modules/spring-data-jpa-query/src/test/resources/projection-insert-data.sql create mode 100644 persistence-modules/spring-data-jpa-query/src/test/resources/test-aggregation-data.sql create mode 100644 persistence-modules/spring-data-jpa-query/src/test/resources/test-fruit-data.sql diff --git a/persistence-modules/spring-data-jpa-query/README.md b/persistence-modules/spring-data-jpa-query/README.md new file mode 100644 index 0000000000..bfff3c0ef3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/README.md @@ -0,0 +1,22 @@ +## Spring Data JPA - Query + +This module contains articles about querying data using Spring Data JPA + +### Relevant Articles: +- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) +- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) +- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) +- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) +- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) +- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) +- [JPA Join Types](https://www.baeldung.com/jpa-join-types) +- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-query/pom.xml b/persistence-modules/spring-data-jpa-query/pom.xml new file mode 100644 index 0000000000..71498143c3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + spring-data-jpa-query + spring-data-jpa-query + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + com.h2database + h2 + + + + net.ttddyy + datasource-proxy + ${datasource-proxy.version} + + + + com.fasterxml.jackson.core + jackson-databind + + + + org.springframework + spring-oxm + + + + + 1.4.1 + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..3ea3d113da --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/Application.java @@ -0,0 +1,13 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java new file mode 100644 index 0000000000..26c2373cbe --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java @@ -0,0 +1,85 @@ +package com.baeldung.aggregation.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import java.util.Objects; + +@Entity +public class Comment { + @Id + private Integer id; + private Integer year; + private boolean approved; + private String content; + @ManyToOne + private Post post; + + public Comment() { + } + + public Comment(int id, int year, boolean approved, String content, Post post) { + this.id = id; + this.year = year; + this.approved = approved; + this.content = content; + this.post = post; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public boolean isApproved() { + return approved; + } + + public void setApproved(boolean approved) { + this.approved = approved; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public Post getPost() { + return post; + } + + public void setPost(Post post) { + this.post = post; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Comment)) { + return false; + } + Comment comment = (Comment) o; + return getId().equals(comment.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java new file mode 100644 index 0000000000..f396e080ae --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java @@ -0,0 +1,75 @@ +package com.baeldung.aggregation.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.List; +import java.util.Objects; + +@Entity +public class Post { + @Id + private Integer id; + private String title; + private String content; + @OneToMany(mappedBy = "post") + private List comments; + + public Post() { + } + + public Post(Integer id, String title, String content) { + this.id = id; + this.title = title; + this.content = content; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Post)) { + return false; + } + Post post = (Post) o; + return getId().equals(post.getId()); + } + + @Override + public int hashCode() { + return Objects.hash(getId()); + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java new file mode 100644 index 0000000000..510b52a47c --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java @@ -0,0 +1,27 @@ +package com.baeldung.aggregation.model.custom; + +public class CommentCount { + private Integer year; + private Long total; + + public CommentCount(Integer year, Long total) { + this.year = year; + this.total = total; + } + + public Integer getYear() { + return year; + } + + public void setYear(Integer year) { + this.year = year; + } + + public Long getTotal() { + return total; + } + + public void setTotal(Long total) { + this.total = total; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java new file mode 100644 index 0000000000..acb25cfd49 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java @@ -0,0 +1,8 @@ +package com.baeldung.aggregation.model.custom; + +public interface ICommentCount { + + Integer getYearComment(); + + Long getTotalComment(); +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java new file mode 100644 index 0000000000..89e9345e94 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.aggregation.repository; + +import com.baeldung.aggregation.model.Comment; +import com.baeldung.aggregation.model.custom.CommentCount; +import com.baeldung.aggregation.model.custom.ICommentCount; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface CommentRepository extends JpaRepository { + + @Query("SELECT c.year, COUNT(c.year) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + List countTotalCommentsByYear(); + + @Query("SELECT new com.baeldung.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + List countTotalCommentsByYearClass(); + + @Query("SELECT c.year AS yearComment, COUNT(c.year) AS totalComment FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + List countTotalCommentsByYearInterface(); + + @Query(value = "SELECT c.year AS yearComment, COUNT(c.*) AS totalComment FROM comment AS c GROUP BY c.year ORDER BY c.year DESC", nativeQuery = true) + List countTotalCommentsByYearNative(); + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java new file mode 100644 index 0000000000..73397ad42e --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import com.baeldung.boot.domain.Article; + +import java.util.Date; +import java.util.List; + +public interface ArticleRepository extends JpaRepository { + + List

findAllByPublicationDate(Date publicationDate); + + List
findAllByPublicationTimeBetween(Date publicationTimeStart, + Date publicationTimeEnd); + + @Query("select a from Article a where a.creationDateTime <= :creationDateTime") + List
findAllWithCreationDateTimeBefore( + @Param("creationDateTime") Date creationDateTime); + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java new file mode 100644 index 0000000000..de4dbed1a0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java @@ -0,0 +1,23 @@ +package com.baeldung.boot.domain; + +import javax.persistence.*; +import java.util.Date; + +@Entity +public class Article { + + @Id + @GeneratedValue + private Integer id; + @Temporal(TemporalType.DATE) + private Date publicationDate; + @Temporal(TemporalType.TIME) + private Date publicationTime; + @Temporal(TemporalType.TIMESTAMP) + private Date creationDateTime; + + public Integer getId() { + return id; + } + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java new file mode 100644 index 0000000000..7152286c83 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.boot.passenger; + +import java.util.List; + +interface CustomPassengerRepository { + + List findOrderedBySeatNumberLimitedTo(int limit); +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/Passenger.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/Passenger.java new file mode 100644 index 0000000000..c75107a783 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/Passenger.java @@ -0,0 +1,82 @@ +package com.baeldung.boot.passenger; + +import javax.persistence.Basic; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import java.util.Objects; + +@Entity +class Passenger { + + @Id + @GeneratedValue + @Column(nullable = false) + private Long id; + + @Basic(optional = false) + @Column(nullable = false) + private String firstName; + + @Basic(optional = false) + @Column(nullable = false) + private String lastName; + + @Basic(optional = false) + @Column(nullable = false) + private Integer seatNumber; + + private Passenger(String firstName, String lastName, Integer seatNumber) { + this.firstName = firstName; + this.lastName = lastName; + this.seatNumber = seatNumber; + } + + static Passenger from(String firstName, String lastName, Integer seatNumber) { + return new Passenger(firstName, lastName, seatNumber); + } + + @Override + public boolean equals(Object object) { + if (this == object) + return true; + if (object == null || getClass() != object.getClass()) + return false; + Passenger passenger = (Passenger) object; + return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName()) + && Objects.equals(getLastName(), passenger.getLastName()); + } + + @Override + public int hashCode() { + return Objects.hash(getFirstName(), getLastName(), getSeatNumber()); + } + + @Override + public String toString() { + final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName()); + toStringBuilder.append("{ id=").append(id); + toStringBuilder.append(", firstName='").append(firstName).append('\''); + toStringBuilder.append(", lastName='").append(lastName).append('\''); + toStringBuilder.append(", seatNumber=").append(seatNumber); + toStringBuilder.append('}'); + return toStringBuilder.toString(); + } + + Long getId() { + return id; + } + + String getFirstName() { + return firstName; + } + + String getLastName() { + return lastName; + } + + Integer getSeatNumber() { + return seatNumber; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java new file mode 100644 index 0000000000..14d5403cb5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.boot.passenger; + +import java.util.List; + +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.repository.JpaRepository; + +interface PassengerRepository extends JpaRepository, CustomPassengerRepository { + + Passenger findFirstByOrderBySeatNumberAsc(); + + Passenger findTopByOrderBySeatNumberAsc(); + + List findByOrderBySeatNumberAsc(); + + List findByFirstNameIgnoreCase(String firstName); + + List findByLastNameOrderBySeatNumberAsc(String lastName); + + List findByLastName(String lastName, Sort sort); + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java new file mode 100644 index 0000000000..508c669066 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java @@ -0,0 +1,20 @@ +package com.baeldung.boot.passenger; + +import org.springframework.stereotype.Repository; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.List; + +@Repository +class PassengerRepositoryImpl implements CustomPassengerRepository { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findOrderedBySeatNumberLimitedTo(int limit) { + return entityManager.createQuery("SELECT p FROM Passenger p ORDER BY p.seatNumber", + Passenger.class).setMaxResults(limit).getResultList(); + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Characteristic.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Characteristic.java new file mode 100644 index 0000000000..ae20375572 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Characteristic.java @@ -0,0 +1,43 @@ +package com.baeldung.entitygraph.model; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Characteristic { + + @Id + private Long id; + private String type; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private Item item; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Item getItem() { + return item; + } + + public void setItem(Item item) { + this.item = item; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Item.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Item.java new file mode 100644 index 0000000000..e90a22ef62 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/model/Item.java @@ -0,0 +1,48 @@ +package com.baeldung.entitygraph.model; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedAttributeNode; +import javax.persistence.NamedEntityGraph; +import javax.persistence.OneToMany; + +@Entity +@NamedEntityGraph(name = "Item.characteristics", + attributeNodes = @NamedAttributeNode("characteristics") +) +public class Item { + + @Id + private Long id; + private String name; + + @OneToMany(mappedBy = "item") + private List characteristics = new ArrayList<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCharacteristics() { + return characteristics; + } + + public void setCharacteristics(List characteristics) { + this.characteristics = characteristics; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java new file mode 100644 index 0000000000..9f923ab241 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.entitygraph.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.entitygraph.model.Characteristic; + +public interface CharacteristicsRepository extends JpaRepository { + + @EntityGraph(attributePaths = {"item"}) + Characteristic findByType(String type); + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java new file mode 100644 index 0000000000..b2a5f223b3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.entitygraph.repository; + +import org.springframework.data.jpa.repository.EntityGraph; +import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.entitygraph.model.Item; + +public interface ItemRepository extends JpaRepository { + + @EntityGraph(value = "Item.characteristics", type = EntityGraphType.FETCH) + Item findByName(String name); +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/Car.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/Car.java new file mode 100644 index 0000000000..bf09caf6ff --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/Car.java @@ -0,0 +1,48 @@ +package com.baeldung.exists; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +/** + * @author paullatzelsperger + * @since 2019-03-20 + */ +@Entity +public class Car { + + @Id + @GeneratedValue + private int id; + private Integer power; + private String model; + + Car() { + + } + + public Car(int power, String model) { + this.power = power; + this.model = model; + } + + public Integer getPower() { + return power; + } + + public void setPower(Integer power) { + this.power = power; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public int getId() { + return id; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/CarRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/CarRepository.java new file mode 100644 index 0000000000..a54f19f4cd --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/exists/CarRepository.java @@ -0,0 +1,24 @@ +package com.baeldung.exists; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +/** + * @author paullatzelsperger + * @since 2019-03-20 + */ +@Repository +public interface CarRepository extends JpaRepository { + + boolean existsCarByPower(int power); + + boolean existsCarByModel(String model); + + @Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model") + boolean existsCarExactCustomQuery(@Param("model") String model); + + @Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)") + boolean existsCarLikeCustomQuery(@Param("model") String model); +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Department.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Department.java new file mode 100644 index 0000000000..439f7532f5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Department.java @@ -0,0 +1,45 @@ +package com.baeldung.joins.model; + +import java.util.List; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private String name; + + @OneToMany(mappedBy = "department") + private List employees; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getEmployees() { + return employees; + } + + public void setEmployees(List employees) { + this.employees = employees; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Employee.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Employee.java new file mode 100644 index 0000000000..277274e61c --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Employee.java @@ -0,0 +1,69 @@ +package com.baeldung.joins.model; + +import java.util.List; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "joins_employee") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + private int age; + + @ManyToOne + private Department department; + + @OneToMany(mappedBy = "employee") + private List phones; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public List getPhones() { + return phones; + } + + public void setPhones(List phones) { + this.phones = phones; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Phone.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Phone.java new file mode 100644 index 0000000000..41382915b1 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/joins/model/Phone.java @@ -0,0 +1,44 @@ +package com.baeldung.joins.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Phone { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String number; + + @ManyToOne + private Employee employee; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String number) { + this.number = number; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/apple-fruit-data.xml b/persistence-modules/spring-data-jpa-query/src/main/resources/apple-fruit-data.xml new file mode 100644 index 0000000000..d87ae28f1e --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/apple-fruit-data.xml @@ -0,0 +1,7 @@ + + + + 1 + apple + red + diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/application-joins.properties b/persistence-modules/spring-data-jpa-query/src/main/resources/application-joins.properties new file mode 100644 index 0000000000..fe2270293b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/application-joins.properties @@ -0,0 +1 @@ +spring.datasource.data=classpath:db/import_joins.sql diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties new file mode 100644 index 0000000000..72fc330767 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/db/import_joins.sql b/persistence-modules/spring-data-jpa-query/src/main/resources/db/import_joins.sql new file mode 100644 index 0000000000..e4772d6ff2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/db/import_joins.sql @@ -0,0 +1,13 @@ +INSERT INTO department (id, name) VALUES (1, 'Infra'); +INSERT INTO department (id, name) VALUES (2, 'Accounting'); +INSERT INTO department (id, name) VALUES (3, 'Management'); + +INSERT INTO joins_employee (id, name, age, department_id) VALUES (1, 'Baeldung', '35', 1); +INSERT INTO joins_employee (id, name, age, department_id) VALUES (2, 'John', '35', 2); +INSERT INTO joins_employee (id, name, age, department_id) VALUES (3, 'Jane', '35', 2); + +INSERT INTO phone (id, number, employee_id) VALUES (1, '111', 1); +INSERT INTO phone (id, number, employee_id) VALUES (2, '222', 1); +INSERT INTO phone (id, number, employee_id) VALUES (3, '333', 1); + +COMMIT; diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/fruit-data.json b/persistence-modules/spring-data-jpa-query/src/main/resources/fruit-data.json new file mode 100644 index 0000000000..6dc44e2586 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/fruit-data.json @@ -0,0 +1,14 @@ +[ + { + "_class": "com.baeldung.entity.Fruit", + "name": "apple", + "color": "red", + "id": 1 + }, + { + "_class": "com.baeldung.entity.Fruit", + "name": "guava", + "color": "green", + "id": 2 + } +] \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/guava-fruit-data.xml b/persistence-modules/spring-data-jpa-query/src/main/resources/guava-fruit-data.xml new file mode 100644 index 0000000000..ffd75bb4bb --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/guava-fruit-data.xml @@ -0,0 +1,7 @@ + + + + 2 + guava + green + diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql b/persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql new file mode 100644 index 0000000000..4fe18bf4aa --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql @@ -0,0 +1,3 @@ +insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); +insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java new file mode 100644 index 0000000000..779ade7a3f --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java @@ -0,0 +1,107 @@ +package com.baeldung.aggregation; + +import com.baeldung.aggregation.model.custom.CommentCount; +import com.baeldung.aggregation.model.custom.ICommentCount; +import com.baeldung.aggregation.repository.CommentRepository; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringRunner.class) +@DataJpaTest + +@Sql(scripts = "/test-aggregation-data.sql") +public class SpringDataAggregateIntegrationTest { + + @Autowired + private CommentRepository commentRepository; + + @Test + public void whenQueryWithAggregation_thenReturnResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYear(); + + Object[] countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019[0], is(Integer.valueOf(2019))); + assertThat(countYear2019[1], is(1l)); + + Object[] countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018[0], is(Integer.valueOf(2018))); + assertThat(countYear2018[1], is(2l)); + + Object[] countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017[0], is(Integer.valueOf(2017))); + assertThat(countYear2017[1], is(1l)); + } + + @Test + public void whenQueryWithAggregation_thenReturnCustomResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYearClass(); + + CommentCount countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019.getYear(), is(Integer.valueOf(2019))); + assertThat(countYear2019.getTotal(), is(1l)); + + CommentCount countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018.getYear(), is(Integer.valueOf(2018))); + assertThat(countYear2018.getTotal(), is(2l)); + + CommentCount countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017.getYear(), is(Integer.valueOf(2017))); + assertThat(countYear2017.getTotal(), is(1l)); + } + + @Test + public void whenQueryWithAggregation_thenReturnInterfaceResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYearInterface(); + + ICommentCount countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); + assertThat(countYear2019.getTotalComment(), is(1l)); + + ICommentCount countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); + assertThat(countYear2018.getTotalComment(), is(2l)); + + ICommentCount countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); + assertThat(countYear2017.getTotalComment(), is(1l)); + } + + @Test + public void whenNativeQueryWithAggregation_thenReturnInterfaceResult() { + List commentCountsByYear = commentRepository.countTotalCommentsByYearNative(); + + ICommentCount countYear2019 = commentCountsByYear.get(0); + + assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); + assertThat(countYear2019.getTotalComment(), is(1l)); + + ICommentCount countYear2018 = commentCountsByYear.get(1); + + assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); + assertThat(countYear2018.getTotalComment(), is(2l)); + + ICommentCount countYear2017 = commentCountsByYear.get(2); + + assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); + assertThat(countYear2017.getTotalComment(), is(1l)); + } + +} diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java new file mode 100644 index 0000000000..20fc3cbeaf --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java @@ -0,0 +1,67 @@ +package com.baeldung.boot.daos; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.domain.Article; + +@RunWith(SpringRunner.class) +@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") +public class ArticleRepositoryIntegrationTest { + + @Autowired + private ArticleRepository repository; + + @Test + public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned() + throws Exception { + List
result = repository.findAllByPublicationDate( + new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(1, 2).contains(id)) + ); + } + + @Test + public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned() + throws Exception { + List
result = repository.findAllByPublicationTimeBetween( + new SimpleDateFormat("HH:mm").parse("15:15"), + new SimpleDateFormat("HH:mm").parse("16:30") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(2, 3).contains(id)) + ); + } + + @Test + public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception { + List
result = repository.findAllWithCreationDateTimeBefore( + new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00") + ); + + assertEquals(2, result.size()); + assertTrue(result.stream() + .map(Article::getId) + .allMatch(id -> Arrays.asList(2, 3).contains(id)) + ); + } + +} diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java new file mode 100644 index 0000000000..f082350019 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java @@ -0,0 +1,190 @@ +package com.baeldung.boot.passenger; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.passenger.Passenger; +import com.baeldung.boot.passenger.PassengerRepository; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + + +@DataJpaTest +@RunWith(SpringRunner.class) +public class PassengerRepositoryIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + @Autowired + private PassengerRepository repository; + + @Before + public void before() { + entityManager.persist(Passenger.from("Jill", "Smith", 50)); + entityManager.persist(Passenger.from("Eve", "Jackson", 95)); + entityManager.persist(Passenger.from("Fred", "Bloggs", 22)); + entityManager.persist(Passenger.from("Ricki", "Bobbie", 36)); + entityManager.persist(Passenger.from("Siya", "Kolisi", 85)); + } + + @Test + public void givenSeveralPassengersWhenOrderedBySeatNumberLimitedToThenThePassengerInTheFirstFilledSeatIsReturned() { + Passenger expected = Passenger.from("Fred", "Bloggs", 22); + + List passengers = repository.findOrderedBySeatNumberLimitedTo(1); + + assertEquals(1, passengers.size()); + + Passenger actual = passengers.get(0); + assertEquals(expected, actual); + } + + @Test + public void givenSeveralPassengersWhenFindFirstByOrderBySeatNumberAscThenThePassengerInTheFirstFilledSeatIsReturned() { + Passenger expected = Passenger.from("Fred", "Bloggs", 22); + + Passenger actual = repository.findFirstByOrderBySeatNumberAsc(); + + assertEquals(expected, actual); + } + + @Test + public void givenSeveralPassengersWhenFindPageSortedByThenThePassengerInTheFirstFilledSeatIsReturned() { + Passenger expected = Passenger.from("Fred", "Bloggs", 22); + + Page page = repository.findAll(PageRequest.of(0, 1, + Sort.by(Sort.Direction.ASC, "seatNumber"))); + + assertEquals(1, page.getContent().size()); + + Passenger actual = page.getContent().get(0); + assertEquals(expected, actual); + } + + @Test + public void givenPassengers_whenOrderedBySeatNumberAsc_thenCorrectOrder() { + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + + List passengers = repository.findByOrderBySeatNumberAsc(); + + assertThat(passengers, contains(fred, ricki, jill, siya, eve)); + } + + @Test + public void givenPassengers_whenFindAllWithSortBySeatNumberAsc_thenCorrectOrder() { + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + + List passengers = repository.findAll(Sort.by(Sort.Direction.ASC, "seatNumber")); + + assertThat(passengers, contains(fred, ricki, jill, siya, eve)); + } + + @Test + public void givenPassengers_whenFindByExampleDefaultMatcher_thenExpectedReturned() { + Example example = Example.of(Passenger.from("Fred", "Bloggs", null)); + + Optional actual = repository.findOne(example); + + assertTrue(actual.isPresent()); + assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get()); + } + + @Test + public void givenPassengers_whenFindByExampleCaseInsensitiveMatcher_thenExpectedReturned() { + ExampleMatcher caseInsensitiveExampleMatcher = ExampleMatcher.matchingAll().withIgnoreCase(); + Example example = Example.of(Passenger.from("fred", "bloggs", null), + caseInsensitiveExampleMatcher); + + Optional actual = repository.findOne(example); + + assertTrue(actual.isPresent()); + assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get()); + } + + @Test + public void givenPassengers_whenFindByExampleCustomMatcher_thenExpectedReturned() { + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + + ExampleMatcher customExampleMatcher = ExampleMatcher.matchingAny().withMatcher("firstName", + ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()).withMatcher("lastName", + ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()); + + Example example = Example.of(Passenger.from("e", "s", null), + customExampleMatcher); + + List passengers = repository.findAll(example); + + assertThat(passengers, contains(jill, eve, fred, siya)); + assertThat(passengers, not(contains(ricki))); + } + + @Test + public void givenPassengers_whenFindByIgnoringMatcher_thenExpectedReturned() { + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + + ExampleMatcher ignoringExampleMatcher = ExampleMatcher.matchingAny().withMatcher("lastName", + ExampleMatcher.GenericPropertyMatchers.startsWith().ignoreCase()).withIgnorePaths("firstName", "seatNumber"); + + Example example = Example.of(Passenger.from(null, "b", null), + ignoringExampleMatcher); + + List passengers = repository.findAll(example); + + assertThat(passengers, contains(fred, ricki)); + assertThat(passengers, not(contains(jill))); + assertThat(passengers, not(contains(eve))); + assertThat(passengers, not(contains(siya))); + } + + @Test + public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { + Passenger jill = Passenger.from("Jill", "Smith", 50); + Passenger eve = Passenger.from("Eve", "Jackson", 95); + Passenger fred = Passenger.from("Fred", "Bloggs", 22); + Passenger siya = Passenger.from("Siya", "Kolisi", 85); + Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); + + List passengers = repository.findByFirstNameIgnoreCase("FRED"); + + assertThat(passengers, contains(fred)); + assertThat(passengers, not(contains(eve))); + assertThat(passengers, not(contains(siya))); + assertThat(passengers, not(contains(jill))); + assertThat(passengers, not(contains(ricki))); + + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java new file mode 100644 index 0000000000..24880a5dff --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.entitygraph; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.entitygraph.model.Characteristic; +import com.baeldung.entitygraph.model.Item; +import com.baeldung.entitygraph.repository.CharacteristicsRepository; +import com.baeldung.entitygraph.repository.ItemRepository; + +@DataJpaTest +@RunWith(SpringRunner.class) +@Sql(scripts = "/entitygraph-data.sql") +public class EntityGraphIntegrationTest { + + @Autowired + private ItemRepository itemRepo; + + @Autowired + private CharacteristicsRepository characteristicsRepo; + + @Test + public void givenEntityGraph_whenCalled_shouldRetrunDefinedFields() { + Item item = itemRepo.findByName("Table"); + assertThat(item.getId()).isEqualTo(1L); + } + + @Test + public void givenAdhocEntityGraph_whenCalled_shouldRetrunDefinedFields() { + Characteristic characteristic = characteristicsRepo.findByType("Rigid"); + assertThat(characteristic.getId()).isEqualTo(1L); + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java new file mode 100644 index 0000000000..d99f6671a3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.exists; + +import com.baeldung.Application; +import org.junit.After; +import org.junit.Before; +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.data.domain.Example; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.ignoreCase; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {Application.class}) +public class CarRepositoryIntegrationTest { + + @Autowired + private CarRepository repository; + private int searchId; + + @Before + public void setup() { + List cars = repository.saveAll(Arrays.asList(new Car(200, "BMW"), new Car(300, "Audi"))); + searchId = cars.get(0).getId(); + } + + @After + public void teardown() { + repository.deleteAll(); + } + + @Test + public void whenIdIsCorrect_thenExistsShouldReturnTrue() { + assertThat(repository.existsById(searchId)).isTrue(); + } + + @Test + public void givenExample_whenExists_thenIsTrue() { + ExampleMatcher modelMatcher = ExampleMatcher.matching() + .withIgnorePaths("id") // must explicitly ignore -> PK + .withMatcher("model", ignoreCase()); + Car probe = new Car(); + probe.setModel("bmw"); + + Example example = Example.of(probe, modelMatcher); + + assertThat(repository.exists(example)).isTrue(); + } + + @Test + public void givenPower_whenExists_thenIsFalse() { + assertThat(repository.existsCarByPower(200)).isTrue(); + assertThat(repository.existsCarByPower(800)).isFalse(); + } + + @Test + public void existsByDerivedQuery_byModel() { + assertThat(repository.existsCarByModel("Audi")).isTrue(); + assertThat(repository.existsCarByModel("audi")).isFalse(); + assertThat(repository.existsCarByModel("AUDI")).isFalse(); + assertThat(repository.existsCarByModel("")).isFalse(); + } + + @Test + public void givenModelName_whenExistsExact_thenIsTrue() { + assertThat(repository.existsCarExactCustomQuery("BMW")).isTrue(); + assertThat(repository.existsCarExactCustomQuery("Bmw")).isFalse(); + assertThat(repository.existsCarExactCustomQuery("bmw")).isFalse(); + assertThat(repository.existsCarExactCustomQuery("")).isFalse(); + } + + @Test + public void givenModelName_whenExistsLike_thenIsTrue() { + assertThat(repository.existsCarLikeCustomQuery("BMW")).isTrue(); + assertThat(repository.existsCarLikeCustomQuery("Bmw")).isTrue(); + assertThat(repository.existsCarLikeCustomQuery("bmw")).isTrue(); + assertThat(repository.existsCarLikeCustomQuery("")).isFalse(); + } + +} diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java new file mode 100644 index 0000000000..9b0d23f3e4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java @@ -0,0 +1,142 @@ +package com.baeldung.joins; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.joins.model.Department; +import com.baeldung.joins.model.Phone; +import java.util.Collection; +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@DataJpaTest +@ActiveProfiles("joins") +public class JpaJoinsIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + + @Test + public void whenPathExpressionIsUsedForSingleValuedAssociation_thenCreatesImplicitInnerJoin() { + TypedQuery query = entityManager.createQuery("SELECT e.department FROM Employee e", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Accounting"); + } + + @Test + public void whenJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() { + TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e JOIN e.department d", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Accounting"); + } + + @Test + public void whenInnerJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() { + TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e INNER JOIN e.department d", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Accounting"); + } + + @Test + public void whenEntitiesAreListedInFromAndMatchedInWhere_ThenCreatesJoin() { + TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e, Department d WHERE e.department = d", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Accounting"); + } + + @Test + public void whenEntitiesAreListedInFrom_ThenCreatesCartesianProduct() { + TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e, Department d", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(9); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Management", "Infra", "Accounting", "Management", "Infra", "Accounting", "Management"); + } + + @Test + public void whenCollectionValuedAssociationIsJoined_ThenCanSelect() { + TypedQuery query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.phones ph WHERE ph LIKE '1%'", Phone.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(1); + } + + @Test + public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() { + TypedQuery query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.department d JOIN e.phones ph WHERE d.name IS NOT NULL", Phone.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("number") + .containsOnly("111", "222", "333"); + } + + @Test + public void whenLeftKeywordIsSpecified_thenCreatesOuterJoinAndIncludesNonMatched() { + TypedQuery query = entityManager.createQuery("SELECT DISTINCT d FROM Department d LEFT JOIN d.employees e", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Management"); + } + + @Test + public void whenFetchKeywordIsSpecified_ThenCreatesFetchJoin() { + TypedQuery query = entityManager.createQuery("SELECT d FROM Department d JOIN FETCH d.employees", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(3); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Accounting"); + } + + @Test + public void whenLeftAndFetchKeywordsAreSpecified_ThenCreatesOuterFetchJoin() { + TypedQuery query = entityManager.createQuery("SELECT d FROM Department d LEFT JOIN FETCH d.employees", Department.class); + + List resultList = query.getResultList(); + + assertThat(resultList).hasSize(4); + assertThat(resultList).extracting("name") + .containsOnly("Infra", "Accounting", "Accounting", "Management"); + } + + @Test + public void whenCollectionValuedAssociationIsSpecifiedInSelect_ThenReturnsCollections() { + TypedQuery query = entityManager.createQuery("SELECT e.phones FROM Employee e", Collection.class); + + List resultList = query.getResultList(); + + assertThat(resultList).extracting("number").containsOnly("111", "222", "333"); + } +} diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/entitygraph-data.sql b/persistence-modules/spring-data-jpa-query/src/test/resources/entitygraph-data.sql new file mode 100644 index 0000000000..685ec2c605 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/entitygraph-data.sql @@ -0,0 +1,7 @@ +INSERT INTO Item(id,name) VALUES (1,'Table'); +INSERT INTO Item(id,name) VALUES (2,'Bottle'); + +INSERT INTO Characteristic(id,item_id, type) VALUES (1,1,'Rigid'); +INSERT INTO Characteristic(id,item_id,type) VALUES (2,1,'Big'); +INSERT INTO Characteristic(id,item_id,type) VALUES (3,2,'Fragile'); +INSERT INTO Characteristic(id,item_id,type) VALUES (4,2,'Small'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/projection-clean-up-data.sql b/persistence-modules/spring-data-jpa-query/src/test/resources/projection-clean-up-data.sql new file mode 100644 index 0000000000..d34f6f0636 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/projection-clean-up-data.sql @@ -0,0 +1,2 @@ +DELETE FROM address; +DELETE FROM person; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/projection-insert-data.sql b/persistence-modules/spring-data-jpa-query/src/test/resources/projection-insert-data.sql new file mode 100644 index 0000000000..544dcc4b88 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/projection-insert-data.sql @@ -0,0 +1,2 @@ +INSERT INTO person(id,first_name,last_name) VALUES (1,'John','Doe'); +INSERT INTO address(id,person_id,state,city,street,zip_code) VALUES (1,1,'CA', 'Los Angeles', 'Standford Ave', '90001'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/test-aggregation-data.sql b/persistence-modules/spring-data-jpa-query/src/test/resources/test-aggregation-data.sql new file mode 100644 index 0000000000..12409a124e --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/test-aggregation-data.sql @@ -0,0 +1,7 @@ +INSERT INTO post (id, title, content) VALUES (1, 'Comment 1', 'Content 1'); +INSERT INTO post (id, title, content) VALUES (2, 'Comment 2', 'Content 2'); +INSERT INTO post (id, title, content) VALUES (3, 'Comment 3', 'Content 3'); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (1, 2019, false, 'Comment 1', 1); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (2, 2018, true, 'Comment 2', 1); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (3, 2018, true, 'Comment 3', 2); +INSERT INTO comment (id, year, approved, content, post_id) VALUES (4, 2017, false, 'Comment 4', 3); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/test-fruit-data.sql b/persistence-modules/spring-data-jpa-query/src/test/resources/test-fruit-data.sql new file mode 100644 index 0000000000..d99f42e5a7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query/src/test/resources/test-fruit-data.sql @@ -0,0 +1,6 @@ +truncate table fruit; + +insert into fruit(id,name,color) values (1,'apple','red'); +insert into fruit(id,name,color) values (2,'custard apple','green'); +insert into fruit(id,name,color) values (3,'mango','yellow'); +insert into fruit(id,name,color) values (4,'guava','green'); \ No newline at end of file From 733d901d46437653a81771f4023620b507ea011d Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:31:28 +0530 Subject: [PATCH 056/155] JAVA-66: New module spring-data-jpa-repo --- .../spring-data-jpa-repo/README.md | 22 +++ .../spring-data-jpa-repo/pom.xml | 52 ++++++ .../main/java/com/baeldung/Application.java | 17 ++ .../boot/daos/CustomItemRepository.java | 16 ++ .../boot/daos/CustomItemTypeRepository.java | 13 ++ .../boot/daos/ExtendedRepository.java | 14 ++ .../boot/daos/ExtendedStudentRepository.java | 6 + .../boot/daos/InventoryRepository.java | 8 + .../boot/daos/ItemTypeRepository.java | 10 + .../boot/daos/LocationRepository.java | 10 + .../boot/daos/ReadOnlyLocationRepository.java | 15 ++ .../baeldung/boot/daos/StoreRepository.java | 13 ++ .../daos/impl/CustomItemRepositoryImpl.java | 33 ++++ .../impl/CustomItemTypeRepositoryImpl.java | 27 +++ .../daos/impl/ExtendedRepositoryImpl.java | 37 ++++ .../java/com/baeldung/boot/domain/Item.java | 81 +++++++++ .../com/baeldung/boot/domain/ItemType.java | 46 +++++ .../java/com/baeldung/boot/domain/KVTag.java | 34 ++++ .../com/baeldung/boot/domain/Location.java | 55 ++++++ .../boot/domain/MerchandiseEntity.java | 66 +++++++ .../com/baeldung/boot/domain/SkillTag.java | 30 +++ .../java/com/baeldung/boot/domain/Store.java | 76 ++++++++ .../com/baeldung/boot/domain/Student.java | 74 ++++++++ .../com/baeldung/config/JpaPopulators.java | 35 ++++ .../derivedquery/QueryApplication.java | 13 ++ .../baeldung/derivedquery/entity/User.java | 70 +++++++ .../repository/UserRepository.java | 60 ++++++ .../main/java/com/baeldung/entity/Fruit.java | 40 ++++ .../java/com/baeldung/entity/Passenger.java | 78 ++++++++ .../main/java/com/baeldung/entity/Song.java | 75 ++++++++ .../com/baeldung/like/LikeApplication.java | 13 ++ .../java/com/baeldung/like/model/Movie.java | 58 ++++++ .../like/repository/MovieRepository.java | 41 +++++ .../baeldung/repository/FruitRepository.java | 27 +++ .../repository/PassengerRepository.java | 14 ++ .../baeldung/repository/SongRepository.java | 22 +++ .../StoredProcedureApplication.java | 13 ++ .../controller/CarController.java | 47 +++++ .../baeldung/storedprocedure/entity/Car.java | 41 +++++ .../repository/CarRepository.java | 34 ++++ .../storedprocedure/service/CarService.java | 39 ++++ .../src/main/resources/apple-fruit-data.xml | 7 + .../src/main/resources/application.properties | 5 + .../src/main/resources/car-mysql.sql | 27 +++ .../src/main/resources/fruit-data.json | 14 ++ .../src/main/resources/guava-fruit-data.xml | 7 + .../src/main/resources/import_entities.sql | 17 ++ ...endedStudentRepositoryIntegrationTest.java | 41 +++++ .../InventoryRepositoryIntegrationTest.java | 61 +++++++ .../daos/JpaRepositoriesIntegrationTest.java | 93 ++++++++++ .../UserRepositoryIntegrationTest.java | 172 ++++++++++++++++++ .../like/MovieRepositoryIntegrationTest.java | 87 +++++++++ .../FruitPopulatorIntegrationTest.java | 38 ++++ .../PassengerRepositoryIntegrationTest.java | 56 ++++++ .../SongRepositoryIntegrationTest.java | 59 ++++++ .../resources/application-test.properties | 2 + .../src/test/resources/test-movie-cleanup.sql | 1 + .../src/test/resources/test-movie-data.sql | 7 + .../src/test/resources/test-song-data.sql | 8 + 59 files changed, 2177 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-repo/README.md create mode 100644 persistence-modules/spring-data-jpa-repo/pom.xml create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/InventoryRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/LocationRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/StoreRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Item.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/ItemType.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/KVTag.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Location.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/SkillTag.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Store.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Student.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/controller/CarController.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/entity/Car.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/service/CarService.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/apple-fruit-data.xml create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/car-mysql.sql create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/guava-fruit-data.xml create mode 100644 persistence-modules/spring-data-jpa-repo/src/main/resources/import_entities.sql create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql create mode 100644 persistence-modules/spring-data-jpa-repo/src/test/resources/test-song-data.sql diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md new file mode 100644 index 0000000000..284a7ac2b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -0,0 +1,22 @@ +## Spring Data JPA - Repo + +This module contains articles about repositories in Spring Data JPA + +### Relevant Articles: +- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) +- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) +- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) +- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) +- [Spring Data JPA – Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories) +- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) +- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) +- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) + +### Eclipse Config +After importing the project into Eclipse, you may see the following error: +"No persistence xml file found in project" + +This can be ignored: +- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" +Or: +- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-repo/pom.xml b/persistence-modules/spring-data-jpa-repo/pom.xml new file mode 100644 index 0000000000..984bc1bdff --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + spring-data-jpa-repo + spring-data-jpa-repo + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + + mysql + mysql-connector-java + + + + org.postgresql + postgresql + + + + com.h2database + h2 + + + + org.springframework + spring-oxm + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java new file mode 100644 index 0000000000..47a18b557f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java @@ -0,0 +1,17 @@ +package com.baeldung; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import com.baeldung.boot.daos.impl.ExtendedRepositoryImpl; + +@SpringBootApplication +@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java new file mode 100644 index 0000000000..0aebe34921 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java @@ -0,0 +1,16 @@ +package com.baeldung.boot.daos; + +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.domain.Item; + +@Repository +public interface CustomItemRepository { + + void deleteCustom(Item entity); + + Item findItemById(Long id); + + void findThenDelete(Long id); + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java new file mode 100644 index 0000000000..832d61408c --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.boot.daos; + +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.domain.ItemType; + +@Repository +public interface CustomItemTypeRepository { + + void deleteCustom(ItemType entity); + + void findThenDelete(Long id); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java new file mode 100644 index 0000000000..adb2af4320 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.daos; + +import java.io.Serializable; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface ExtendedRepository extends JpaRepository { + + List findByAttributeContainsText(String attributeName, String text); + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java new file mode 100644 index 0000000000..c9b0192536 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.boot.daos; + +import com.baeldung.boot.domain.Student; + +public interface ExtendedStudentRepository extends ExtendedRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/InventoryRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/InventoryRepository.java new file mode 100644 index 0000000000..606f3993d5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/InventoryRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.repository.CrudRepository; + +import com.baeldung.boot.domain.MerchandiseEntity; + +public interface InventoryRepository extends CrudRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java new file mode 100644 index 0000000000..413c09e968 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.domain.ItemType; + +@Repository +public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/LocationRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/LocationRepository.java new file mode 100644 index 0000000000..697ce295d0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/LocationRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.boot.daos; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.domain.Location; + +@Repository +public interface LocationRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java new file mode 100644 index 0000000000..3a2ea3cda5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.boot.daos; + +import java.util.Optional; + +import org.springframework.data.repository.Repository; + +import com.baeldung.boot.domain.Location; + +@org.springframework.stereotype.Repository +public interface ReadOnlyLocationRepository extends Repository { + + Optional findById(Long id); + + Location save(Location location); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/StoreRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/StoreRepository.java new file mode 100644 index 0000000000..ae13f75f66 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/StoreRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.boot.daos; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.domain.Store; + +@Repository +public interface StoreRepository extends JpaRepository { + List findStoreByLocationId(Long locationId); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java new file mode 100644 index 0000000000..820a2cdd41 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java @@ -0,0 +1,33 @@ +package com.baeldung.boot.daos.impl; + +import javax.persistence.EntityManager; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.daos.CustomItemRepository; +import com.baeldung.boot.domain.Item; + +@Repository +public class CustomItemRepositoryImpl implements CustomItemRepository { + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(Item item) { + entityManager.remove(item); + } + + @Override + public Item findItemById(Long id) { + return entityManager.find(Item.class, id); + } + + @Override + public void findThenDelete(Long id) { + final Item item = entityManager.find(Item.class, id); + entityManager.remove(item); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java new file mode 100644 index 0000000000..e057f36b26 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java @@ -0,0 +1,27 @@ +package com.baeldung.boot.daos.impl; + +import javax.persistence.EntityManager; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.baeldung.boot.daos.CustomItemTypeRepository; +import com.baeldung.boot.domain.ItemType; + +@Repository +public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { + + @Autowired + private EntityManager entityManager; + + @Override + public void deleteCustom(ItemType itemType) { + entityManager.remove(itemType); + } + + @Override + public void findThenDelete(Long id) { + ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); + entityManager.remove(itemTypeToDelete); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java new file mode 100644 index 0000000000..fbe6695844 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java @@ -0,0 +1,37 @@ +package com.baeldung.boot.daos.impl; + +import java.io.Serializable; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import javax.transaction.Transactional; + +import org.springframework.data.jpa.repository.support.JpaEntityInformation; +import org.springframework.data.jpa.repository.support.SimpleJpaRepository; + +import com.baeldung.boot.daos.ExtendedRepository; + +public class ExtendedRepositoryImpl extends SimpleJpaRepository implements ExtendedRepository { + + private EntityManager entityManager; + + public ExtendedRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { + super(entityInformation, entityManager); + this.entityManager = entityManager; + } + + @Transactional + public List findByAttributeContainsText(String attributeName, String text) { + CriteriaBuilder builder = entityManager.getCriteriaBuilder(); + CriteriaQuery query = builder.createQuery(getDomainClass()); + Root root = query.from(getDomainClass()); + query.select(root).where(builder.like(root. get(attributeName), "%" + text + "%")); + TypedQuery q = entityManager.createQuery(query); + return q.getResultList(); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Item.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Item.java new file mode 100644 index 0000000000..8ac06af15a --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Item.java @@ -0,0 +1,81 @@ +package com.baeldung.boot.domain; + +import java.math.BigDecimal; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Item { + + private String color; + private String grade; + + @Id + private Long id; + + @ManyToOne + private ItemType itemType; + + private String name; + private BigDecimal price; + @ManyToOne + private Store store; + + public String getColor() { + return color; + } + + public String getGrade() { + return grade; + } + + public Long getId() { + return id; + } + + public ItemType getItemType() { + return itemType; + } + + public String getName() { + return name; + } + + public BigDecimal getPrice() { + return price; + } + + public Store getStore() { + return store; + } + + public void setColor(String color) { + this.color = color; + } + + public void setGrade(String grade) { + this.grade = grade; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItemType(ItemType itemType) { + this.itemType = itemType; + } + + public void setName(String name) { + this.name = name; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public void setStore(Store store) { + this.store = store; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/ItemType.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/ItemType.java new file mode 100644 index 0000000000..8a52a9847c --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/ItemType.java @@ -0,0 +1,46 @@ +package com.baeldung.boot.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; + +@Entity +public class ItemType { + + @Id + private Long id; + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "ITEM_TYPE_ID") + private List items = new ArrayList<>(); + + private String name; + + public Long getId() { + return id; + } + + public List getItems() { + return items; + } + + public String getName() { + return name; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItems(List items) { + this.items = items; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/KVTag.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/KVTag.java new file mode 100644 index 0000000000..1901f43c0a --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/KVTag.java @@ -0,0 +1,34 @@ +package com.baeldung.boot.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class KVTag { + private String key; + private String value; + + public KVTag() { + } + + public KVTag(String key, String value) { + super(); + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Location.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Location.java new file mode 100644 index 0000000000..9c1b93d551 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Location.java @@ -0,0 +1,55 @@ +package com.baeldung.boot.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; + +@Entity +public class Location { + + private String city; + private String country; + @Id + private Long id; + + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "LOCATION_ID") + private List stores = new ArrayList<>(); + + public String getCity() { + return city; + } + + public String getCountry() { + return country; + } + + public Long getId() { + return id; + } + + public List getStores() { + return stores; + } + + public void setCity(String city) { + this.city = city; + } + + public void setCountry(String country) { + this.country = country; + } + + public void setId(Long id) { + this.id = id; + } + + public void setStores(List stores) { + this.stores = stores; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java new file mode 100644 index 0000000000..e94c23de86 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java @@ -0,0 +1,66 @@ +package com.baeldung.boot.domain; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.math.BigDecimal; + +@Entity +public class MerchandiseEntity { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private BigDecimal price; + + private String brand; + + public MerchandiseEntity() { + } + + public MerchandiseEntity(String title, BigDecimal price) { + this.title = title; + this.price = price; + } + + public Long getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(BigDecimal price) { + this.price = price; + } + + public String getBrand() { + return brand; + } + + public void setBrand(String brand) { + this.brand = brand; + } + + @Override + public String toString() { + return "MerchandiseEntity{" + + "id=" + id + + ", title='" + title + '\'' + + ", price=" + price + + ", brand='" + brand + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/SkillTag.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/SkillTag.java new file mode 100644 index 0000000000..0933a3e6af --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/SkillTag.java @@ -0,0 +1,30 @@ +package com.baeldung.boot.domain; + +import javax.persistence.Embeddable; + +@Embeddable +public class SkillTag { + private String name; + private int value; + + public SkillTag() { + } + + public SkillTag(String name, int value) { + super(); + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public void setValue(int value) { + this.value = value; + } + + public String getName() { + return name; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Store.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Store.java new file mode 100644 index 0000000000..5b4b831cc7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Store.java @@ -0,0 +1,76 @@ +package com.baeldung.boot.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +@Entity +public class Store { + + private Boolean active; + @Id + private Long id; + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "STORE_ID") + private List items = new ArrayList<>(); + private Long itemsSold; + + @ManyToOne + private Location location; + + private String name; + + public Boolean getActive() { + return active; + } + + public Long getId() { + return id; + } + + public List getItems() { + return items; + } + + public Long getItemsSold() { + return itemsSold; + } + + public Location getLocation() { + return location; + } + + public String getName() { + return name; + } + + public void setActive(Boolean active) { + this.active = active; + } + + public void setId(Long id) { + this.id = id; + } + + public void setItems(List items) { + this.items = items; + } + + public void setItemsSold(Long itemsSold) { + this.itemsSold = itemsSold; + } + + public void setLocation(Location location) { + this.location = location; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Student.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Student.java new file mode 100644 index 0000000000..1003167cc7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/domain/Student.java @@ -0,0 +1,74 @@ +package com.baeldung.boot.domain; + +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import java.util.ArrayList; +import java.util.List; + +@Entity +public class Student { + + @Id + private long id; + private String name; + + @ElementCollection + private List tags = new ArrayList<>(); + + @ElementCollection + private List skillTags = new ArrayList<>(); + + @ElementCollection + private List kvTags = new ArrayList<>(); + + public Student() { + } + + public Student(long id, String name) { + super(); + this.id = id; + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags.addAll(tags); + } + + public List getSkillTags() { + return skillTags; + } + + public void setSkillTags(List skillTags) { + this.skillTags.addAll(skillTags); + } + + public List getKVTags() { + return this.kvTags; + } + + public void setKVTags(List kvTags) { + this.kvTags.addAll(kvTags); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java new file mode 100644 index 0000000000..24348d31c5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java @@ -0,0 +1,35 @@ +package com.baeldung.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean; +import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +import com.baeldung.entity.Fruit; + +@Configuration +public class JpaPopulators { + + @Bean + public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception { + Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean(); + factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") }); + return factory; + } + + @Bean + public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() { + + Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller(); + unmarshaller.setClassesToBeBound(Fruit.class); + + UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean(); + factory.setUnmarshaller(unmarshaller); + factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") }); + return factory; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java new file mode 100644 index 0000000000..d7a1950305 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.derivedquery; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class QueryApplication { + + public static void main(String[] args) { + SpringApplication.run(QueryApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java new file mode 100644 index 0000000000..49e824f09f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java @@ -0,0 +1,70 @@ +package com.baeldung.derivedquery.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; +import java.time.ZonedDateTime; + +@Table(name = "users") +@Entity +public class User { + + @Id + @GeneratedValue + private Integer id; + private String name; + private Integer age; + private ZonedDateTime birthDate; + private Boolean active; + + public User() { + } + + public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) { + this.name = name; + this.age = age; + this.birthDate = birthDate; + this.active = active; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public ZonedDateTime getBirthDate() { + return birthDate; + } + + public void setBirthDate(ZonedDateTime birthDate) { + this.birthDate = birthDate; + } + + public Boolean getActive() { + return active; + } + + public void setActive(Boolean active) { + this.active = active; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java new file mode 100644 index 0000000000..e613ee1531 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java @@ -0,0 +1,60 @@ +package com.baeldung.derivedquery.repository; + +import com.baeldung.derivedquery.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.time.ZonedDateTime; +import java.util.Collection; +import java.util.List; + +public interface UserRepository extends JpaRepository { + + List findByName(String name); + + List findByNameIs(String name); + + List findByNameEquals(String name); + + List findByNameIsNull(); + + List findByNameNot(String name); + + List findByNameIsNot(String name); + + List findByNameStartingWith(String name); + + List findByNameEndingWith(String name); + + List findByNameContaining(String name); + + List findByNameLike(String name); + + List findByAgeLessThan(Integer age); + + List findByAgeLessThanEqual(Integer age); + + List findByAgeGreaterThan(Integer age); + + List findByAgeGreaterThanEqual(Integer age); + + List findByAgeBetween(Integer startAge, Integer endAge); + + List findByBirthDateAfter(ZonedDateTime birthDate); + + List findByBirthDateBefore(ZonedDateTime birthDate); + + List findByActiveTrue(); + + List findByActiveFalse(); + + List findByAgeIn(Collection ages); + + List findByNameOrBirthDate(String name, ZonedDateTime birthDate); + + List findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active); + + List findByNameOrderByName(String name); + + List findByNameOrderByNameDesc(String name); + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java new file mode 100644 index 0000000000..d45ac33db8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java @@ -0,0 +1,40 @@ +package com.baeldung.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +@Entity +public class Fruit { + + @Id + private long id; + private String name; + private String color; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java new file mode 100644 index 0000000000..3aafbe9afa --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java @@ -0,0 +1,78 @@ +package com.baeldung.entity; + +import javax.persistence.Basic; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import java.util.Objects; + +@Entity +public class Passenger { + + @Id + @GeneratedValue + @Column(nullable = false) + private Long id; + + @Basic(optional = false) + @Column(nullable = false) + private String firstName; + + @Basic(optional = false) + @Column(nullable = false) + private String lastName; + + private Passenger(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public static Passenger from(String firstName, String lastName) { + return new Passenger(firstName, lastName); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Passenger passenger = (Passenger) o; + return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, lastName); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java new file mode 100644 index 0000000000..395527c1eb --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java @@ -0,0 +1,75 @@ +package com.baeldung.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import java.time.LocalDateTime; + +@Entity +public class Song { + + @Id private long id; + private String name; + @Column(name = "length_in_seconds") + private int lengthInSeconds; + private String compositor; + private String singer; + private LocalDateTime released; + private String genre; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getLengthInSeconds() { + return lengthInSeconds; + } + + public void setLengthInSeconds(int lengthInSeconds) { + this.lengthInSeconds = lengthInSeconds; + } + + public String getCompositor() { + return compositor; + } + + public void setCompositor(String compositor) { + this.compositor = compositor; + } + + public String getSinger() { + return singer; + } + + public void setSinger(String singer) { + this.singer = singer; + } + + public LocalDateTime getReleased() { + return released; + } + + public void setReleased(LocalDateTime released) { + this.released = released; + } + + public String getGenre() { + return genre; + } + + public void setGenre(String genre) { + this.genre = genre; + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java new file mode 100644 index 0000000000..311aea3001 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/LikeApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.like; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LikeApplication { + + public static void main(String[] args) { + SpringApplication.run(LikeApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java new file mode 100644 index 0000000000..bba8bd35c4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/model/Movie.java @@ -0,0 +1,58 @@ +package com.baeldung.like.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Movie { + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE) + private Long id; + private String title; + private String director; + private String rating; + private int duration; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDirector() { + return director; + } + + public void setDirector(String director) { + this.director = director; + } + + public String getRating() { + return rating; + } + + public void setRating(String rating) { + this.rating = rating; + } + + public int getDuration() { + return duration; + } + + public void setDuration(int duration) { + this.duration = duration; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java new file mode 100644 index 0000000000..241bdd3306 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/like/repository/MovieRepository.java @@ -0,0 +1,41 @@ +package com.baeldung.like.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; + +import com.baeldung.like.model.Movie; + +public interface MovieRepository extends CrudRepository { + + List findByTitleContaining(String title); + + List findByTitleLike(String title); + + List findByTitleContains(String title); + + List findByTitleIsContaining(String title); + + List findByRatingStartsWith(String rating); + + List findByDirectorEndsWith(String director); + + List findByTitleContainingIgnoreCase(String title); + + List findByRatingNotContaining(String rating); + + List findByDirectorNotLike(String director); + + @Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%") + List searchByTitleLike(@Param("title") String title); + + @Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%") + List searchByRatingStartsWith(String rating); + + //Escaping works in SpringBoot >= 2.4.1 + //@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}") + @Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}") + List searchByDirectorEndsWith(String director); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java new file mode 100644 index 0000000000..5055252adf --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.entity.Fruit; + +@Repository +public interface FruitRepository extends JpaRepository { + + Long deleteByName(String name); + + List deleteByColor(String color); + + Long removeByName(String name); + + List removeByColor(String color); + + @Modifying + @Query("delete from Fruit f where f.name=:name or f.color=:color") + int deleteFruits(@Param("name") String name, @Param("color") String color); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java new file mode 100644 index 0000000000..a295a74f1b --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.repository; + +import com.baeldung.entity.Passenger; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +interface PassengerRepository extends JpaRepository { + + List findByFirstNameIgnoreCase(String firstName); + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java new file mode 100644 index 0000000000..6faed411d3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java @@ -0,0 +1,22 @@ +package com.baeldung.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.entity.Song; + +@Repository +public interface SongRepository extends JpaRepository { + + List findByNameLike(String name); + + List findByNameNotLike(String name); + + List findByNameStartingWith(String startingWith); + + List findByNameEndingWith(String endingWith); + + List findBySingerContaining(String singer); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java new file mode 100644 index 0000000000..5f05764e21 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.storedprocedure; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StoredProcedureApplication { + + public static void main(String[] args) { + SpringApplication.run(StoredProcedureApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/controller/CarController.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/controller/CarController.java new file mode 100644 index 0000000000..6aef600d01 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/controller/CarController.java @@ -0,0 +1,47 @@ +package com.baeldung.storedprocedure.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.storedprocedure.entity.Car; +import com.baeldung.storedprocedure.service.CarService; + +@RestController +public class CarController { + @Autowired + private CarService carService; + + @GetMapping(path = "/modelcount") + public long getTotalCarsByModel(@RequestParam("model") String model) { + return carService.getTotalCarsByModel(model); + } + + @GetMapping(path = "/modelcountP") + public long getTotalCarsByModelProcedureName(@RequestParam("model") String model) { + return carService.getTotalCarsByModelProcedureName(model); + } + + @GetMapping(path = "/modelcountV") + public long getTotalCarsByModelVaue(@RequestParam("model") String model) { + return carService.getTotalCarsByModelValue(model); + } + + @GetMapping(path = "/modelcountEx") + public long getTotalCarsByModelExplicit(@RequestParam("model") String model) { + return carService.getTotalCarsByModelExplicit(model); + } + + @GetMapping(path = "/modelcountEn") + public long getTotalCarsByModelEntity(@RequestParam("model") String model) { + return carService.getTotalCarsByModelEntity(model); + } + + @GetMapping(path = "/carsafteryear") + public List findCarsAfterYear(@RequestParam("year") Integer year) { + return carService.findCarsAfterYear(year); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/entity/Car.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/entity/Car.java new file mode 100644 index 0000000000..2817c25ff7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/entity/Car.java @@ -0,0 +1,41 @@ +package com.baeldung.storedprocedure.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedStoredProcedureQuery; +import javax.persistence.StoredProcedureParameter; +import javax.persistence.ParameterMode; + +@Entity +@NamedStoredProcedureQuery(name = "Car.getTotalCardsbyModelEntity", procedureName = "GET_TOTAL_CARS_BY_MODEL", parameters = { + @StoredProcedureParameter(mode = ParameterMode.IN, name = "model_in", type = String.class), + @StoredProcedureParameter(mode = ParameterMode.OUT, name = "count_out", type = Integer.class) }) + +public class Car { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column + private long id; + + @Column + private String model; + + @Column + private Integer year; + + public long getId() { + return id; + } + + public String getModel() { + return model; + } + + public Integer getYear() { + return year; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java new file mode 100644 index 0000000000..3d9428628e --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java @@ -0,0 +1,34 @@ +package com.baeldung.storedprocedure.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.jpa.repository.query.Procedure; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.storedprocedure.entity.Car; + +@Repository +public interface CarRepository extends JpaRepository { + + @Procedure + int GET_TOTAL_CARS_BY_MODEL(String model); + + @Procedure("GET_TOTAL_CARS_BY_MODEL") + int getTotalCarsByModel(String model); + + @Procedure(procedureName = "GET_TOTAL_CARS_BY_MODEL") + int getTotalCarsByModelProcedureName(String model); + + @Procedure(value = "GET_TOTAL_CARS_BY_MODEL") + int getTotalCarsByModelValue(String model); + + @Procedure(name = "Car.getTotalCardsbyModelEntity") + int getTotalCarsByModelEntiy(@Param("model_in") String model); + + @Query(value = "CALL FIND_CARS_AFTER_YEAR(:year_in);", nativeQuery = true) + List findCarsAfterYear(@Param("year_in") Integer year_in); + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/service/CarService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/service/CarService.java new file mode 100644 index 0000000000..104f46e324 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/storedprocedure/service/CarService.java @@ -0,0 +1,39 @@ +package com.baeldung.storedprocedure.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.storedprocedure.entity.Car; +import com.baeldung.storedprocedure.repository.CarRepository; + +@Service +public class CarService { + @Autowired + private CarRepository carRepository; + + public int getTotalCarsByModel(String model) { + return carRepository.getTotalCarsByModel(model); + } + + public int getTotalCarsByModelProcedureName(String model) { + return carRepository.getTotalCarsByModelProcedureName(model); + } + + public int getTotalCarsByModelValue(String model) { + return carRepository.getTotalCarsByModelValue(model); + } + + public int getTotalCarsByModelExplicit(String model) { + return carRepository.GET_TOTAL_CARS_BY_MODEL(model); + } + + public int getTotalCarsByModelEntity(String model) { + return carRepository.getTotalCarsByModelEntiy(model); + } + + public List findCarsAfterYear(Integer year) { + return carRepository.findCarsAfterYear(year); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/apple-fruit-data.xml b/persistence-modules/spring-data-jpa-repo/src/main/resources/apple-fruit-data.xml new file mode 100644 index 0000000000..d87ae28f1e --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/apple-fruit-data.xml @@ -0,0 +1,7 @@ + + + + 1 + apple + red + diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties new file mode 100644 index 0000000000..65d7b0bf29 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/application.properties @@ -0,0 +1,5 @@ +spring.jpa.show-sql=true +#MySql +#spring.datasource.url=jdbc:mysql://localhost:3306/baeldung +#spring.datasource.username=baeldung +#spring.datasource.password=baeldung \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/car-mysql.sql b/persistence-modules/spring-data-jpa-repo/src/main/resources/car-mysql.sql new file mode 100644 index 0000000000..bb4ab2a86e --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/car-mysql.sql @@ -0,0 +1,27 @@ +DROP TABLE IF EXISTS car; + +CREATE TABLE car (id int(10) NOT NULL AUTO_INCREMENT, + model varchar(50) NOT NULL, + year int(4) NOT NULL, + PRIMARY KEY (id)); + +INSERT INTO car (model, year) VALUES ('BMW', 2000); +INSERT INTO car (model, year) VALUES ('BENZ', 2010); +INSERT INTO car (model, year) VALUES ('PORCHE', 2005); +INSERT INTO car (model, year) VALUES ('PORCHE', 2004); + +DELIMITER $$ + +DROP PROCEDURE IF EXISTS FIND_CARS_AFTER_YEAR$$ +CREATE PROCEDURE FIND_CARS_AFTER_YEAR(IN year_in INT) +BEGIN + SELECT * FROM car WHERE year >= year_in ORDER BY year; +END$$ + +DROP PROCEDURE IF EXISTS GET_TOTAL_CARS_BY_MODEL$$ +CREATE PROCEDURE GET_TOTAL_CARS_BY_MODEL(IN model_in VARCHAR(50), OUT count_out INT) +BEGIN + SELECT COUNT(*) into count_out from car WHERE model = model_in; +END$$ + +DELIMITER ; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json b/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json new file mode 100644 index 0000000000..6dc44e2586 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json @@ -0,0 +1,14 @@ +[ + { + "_class": "com.baeldung.entity.Fruit", + "name": "apple", + "color": "red", + "id": 1 + }, + { + "_class": "com.baeldung.entity.Fruit", + "name": "guava", + "color": "green", + "id": 2 + } +] \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/guava-fruit-data.xml b/persistence-modules/spring-data-jpa-repo/src/main/resources/guava-fruit-data.xml new file mode 100644 index 0000000000..ffd75bb4bb --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/guava-fruit-data.xml @@ -0,0 +1,7 @@ + + + + 2 + guava + green + diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/import_entities.sql b/persistence-modules/spring-data-jpa-repo/src/main/resources/import_entities.sql new file mode 100644 index 0000000000..6282fd1481 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/import_entities.sql @@ -0,0 +1,17 @@ +insert into location (id, country, city) values (1, 'Country X', 'City One'); +insert into location (id, country, city) values (2, 'Country X', 'City Two'); +insert into location (id, country, city) values (3, 'Country X', 'City Three'); + +insert into store (id, name, location_id, items_sold, active) values (1, 'Store One', 3, 130000, true); +insert into store (id, name, location_id, items_sold, active) values (2, 'Store Two', 1, 170000, false); + +insert into item_type (id, name) values (1, 'Food'); +insert into item_type (id, name) values (2, 'Furniture'); +insert into item_type (id, name) values (3, 'Electronics'); + +insert into item (id, name, store_id, item_type_id, price, grade, color) values (1, 'Food Item One', 1, 1, 100, 'A', 'Color x'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (2, 'Furniture Item One', 1, 2, 2500, 'B', 'Color y'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (3, 'Food Item Two', 1, 1, 35, 'A', 'Color z'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (5, 'Furniture Item Two', 2, 2, 1600, 'A', 'Color w'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (6, 'Food Item Three', 2, 1, 5, 'B', 'Color a'); +insert into item (id, name, store_id, item_type_id, price, grade, color) values (7, 'Electronics Item One', 2, 3, 999, 'B', 'Color b'); diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java new file mode 100644 index 0000000000..b367b5fdca --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.boot.daos; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import javax.annotation.Resource; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.Application; +import com.baeldung.boot.domain.Student; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = {Application.class}) +@DirtiesContext +public class ExtendedStudentRepositoryIntegrationTest { + @Resource + private ExtendedStudentRepository extendedStudentRepository; + + @Before + public void setup() { + Student student = new Student(1, "john"); + extendedStudentRepository.save(student); + Student student2 = new Student(2, "johnson"); + extendedStudentRepository.save(student2); + Student student3 = new Student(3, "tom"); + extendedStudentRepository.save(student3); + } + + @Test + public void givenStudents_whenFindByName_thenGetOk() { + List students = extendedStudentRepository.findByAttributeContainsText("name", "john"); + assertThat(students.size()).isEqualTo(2); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java new file mode 100644 index 0000000000..22e2c81739 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java @@ -0,0 +1,61 @@ +package com.baeldung.boot.daos; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.math.BigDecimal; + +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 com.baeldung.Application; +import com.baeldung.boot.domain.MerchandiseEntity; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes=Application.class) +public class InventoryRepositoryIntegrationTest { + + private static final String ORIGINAL_TITLE = "Pair of Pants"; + private static final String UPDATED_TITLE = "Branded Luxury Pants"; + private static final String UPDATED_BRAND = "Armani"; + private static final String ORIGINAL_SHORTS_TITLE = "Pair of Shorts"; + + @Autowired + private InventoryRepository repository; + + @Test + public void shouldCreateNewEntryInDB() { + MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); + pants = repository.save(pants); + + MerchandiseEntity shorts = new MerchandiseEntity(ORIGINAL_SHORTS_TITLE, new BigDecimal(3)); + shorts = repository.save(shorts); + + assertNotNull(pants.getId()); + assertNotNull(shorts.getId()); + assertNotEquals(pants.getId(), shorts.getId()); + } + + @Test + public void shouldUpdateExistingEntryInDB() { + MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); + pants = repository.save(pants); + + Long originalId = pants.getId(); + + pants.setTitle(UPDATED_TITLE); + pants.setPrice(BigDecimal.TEN); + pants.setBrand(UPDATED_BRAND); + + MerchandiseEntity result = repository.save(pants); + + assertEquals(originalId, result.getId()); + assertEquals(UPDATED_TITLE, result.getTitle()); + assertEquals(BigDecimal.TEN, result.getPrice()); + assertEquals(UPDATED_BRAND, result.getBrand()); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java new file mode 100644 index 0000000000..9e4b78dce3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.boot.daos; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; + +import java.util.List; +import java.util.Optional; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.boot.domain.Item; +import com.baeldung.boot.domain.ItemType; +import com.baeldung.boot.domain.Location; +import com.baeldung.boot.domain.Store; + +@RunWith(SpringRunner.class) +@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") +public class JpaRepositoriesIntegrationTest { + @Autowired + private LocationRepository locationRepository; + @Autowired + private StoreRepository storeRepository; + @Autowired + private ItemTypeRepository compositeRepository; + @Autowired + private ReadOnlyLocationRepository readOnlyRepository; + + @Test + public void whenSaveLocation_ThenGetSameLocation() { + Location location = new Location(); + location.setId(100L); + location.setCountry("Country H"); + location.setCity("City Hundred"); + location = locationRepository.saveAndFlush(location); + + Location otherLocation = locationRepository.getOne(location.getId()); + assertEquals("Country H", otherLocation.getCountry()); + assertEquals("City Hundred", otherLocation.getCity()); + + locationRepository.delete(otherLocation); + } + + @Test + public void givenLocationId_whenFindStores_thenGetStores() { + List stores = storeRepository.findStoreByLocationId(1L); + assertEquals(1, stores.size()); + } + + @Test + public void givenItemTypeId_whenDeleted_ThenItemTypeDeleted() { + Optional itemType = compositeRepository.findById(1L); + assertTrue(itemType.isPresent()); + compositeRepository.deleteCustom(itemType.get()); + itemType = compositeRepository.findById(1L); + assertFalse(itemType.isPresent()); + } + + @Test + public void givenItemId_whenUsingCustomRepo_ThenDeleteAppropriateEntity() { + Item item = compositeRepository.findItemById(1L); + assertNotNull(item); + compositeRepository.deleteCustom(item); + item = compositeRepository.findItemById(1L); + assertNull(item); + } + + @Test + public void givenItemAndItemType_WhenAmbiguousDeleteCalled_ThenItemTypeDeletedAndNotItem() { + Optional itemType = compositeRepository.findById(1L); + assertTrue(itemType.isPresent()); + Item item = compositeRepository.findItemById(2L); + assertNotNull(item); + + compositeRepository.findThenDelete(1L); + Optional sameItemType = compositeRepository.findById(1L); + assertFalse(sameItemType.isPresent()); + Item sameItem = compositeRepository.findItemById(2L); + assertNotNull(sameItem); + } + + @Test + public void whenCreatingReadOnlyRepo_thenHaveOnlyReadOnlyOperationsAvailable() { + Optional location = readOnlyRepository.findById(1L); + assertNotNull(location); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..2a6e166b88 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java @@ -0,0 +1,172 @@ +package com.baeldung.derivedquery.repository; + +import com.baeldung.derivedquery.QueryApplication; +import com.baeldung.derivedquery.entity.User; +import org.junit.After; +import org.junit.Before; +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.time.ZonedDateTime; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = QueryApplication.class) +public class UserRepositoryIntegrationTest { + + private static final String USER_NAME_ADAM = "Adam"; + private static final String USER_NAME_EVE = "Eve"; + private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now(); + + @Autowired + private UserRepository userRepository; + + @Before + public void setUp() { + + User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true); + User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false); + User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true); + User user4 = new User(null, 30, BIRTHDATE, false); + + userRepository.saveAll(Arrays.asList(user1, user2, user3, user4)); + } + + @After + public void tearDown() { + + userRepository.deleteAll(); + } + + @Test + public void whenFindByName_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size()); + } + + @Test + public void whenFindByNameIsNull_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByNameIsNull().size()); + } + + @Test + public void whenFindByNameNot_thenReturnsCorrectResult() { + + assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName()); + } + + @Test + public void whenFindByNameStartingWith_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByNameStartingWith("A").size()); + } + + @Test + public void whenFindByNameEndingWith_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByNameEndingWith("e").size()); + } + + @Test + public void whenByNameContaining_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByNameContaining("v").size()); + } + + + @Test + public void whenByNameLike_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByNameEndingWith("m").size()); + } + + @Test + public void whenByAgeLessThan_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByAgeLessThan(25).size()); + } + + + @Test + public void whenByAgeLessThanEqual_thenReturnsCorrectResult() { + + assertEquals(3, userRepository.findByAgeLessThanEqual(25).size()); + } + + @Test + public void whenByAgeGreaterThan_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByAgeGreaterThan(25).size()); + } + + @Test + public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size()); + } + + @Test + public void whenByAgeBetween_thenReturnsCorrectResult() { + + assertEquals(4, userRepository.findByAgeBetween(20, 30).size()); + } + + @Test + public void whenByBirthDateAfter_thenReturnsCorrectResult() { + + final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); + assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size()); + } + + @Test + public void whenByBirthDateBefore_thenReturnsCorrectResult() { + + final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); + assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size()); + } + + @Test + public void whenByActiveTrue_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByActiveTrue().size()); + } + + @Test + public void whenByActiveFalse_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByActiveFalse().size()); + } + + + @Test + public void whenByAgeIn_thenReturnsCorrectResult() { + + final List ages = Arrays.asList(20, 25); + assertEquals(3, userRepository.findByAgeIn(ages).size()); + } + + @Test + public void whenByNameOrBirthDate() { + + assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size()); + } + + @Test + public void whenByNameOrBirthDateAndActive() { + + assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size()); + } + + @Test + public void whenByNameOrderByName() { + + assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size()); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java new file mode 100644 index 0000000000..cc96b638ab --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.like; + +import com.baeldung.like.model.Movie; +import com.baeldung.like.repository.MovieRepository; +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.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; + +@RunWith(SpringRunner.class) +@Sql(scripts = { "/test-movie-data.sql" }) +@SpringBootTest(classes = LikeApplication.class) +@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD) +public class MovieRepositoryIntegrationTest { + @Autowired + private MovieRepository movieRepository; + + @Test + public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() { + List results = movieRepository.findByTitleContaining("in"); + assertEquals(3, results.size()); + + results = movieRepository.findByTitleLike("%in%"); + assertEquals(3, results.size()); + + results = movieRepository.findByTitleIsContaining("in"); + assertEquals(3, results.size()); + + results = movieRepository.findByTitleContains("in"); + assertEquals(3, results.size()); + } + + @Test + public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() { + List results = movieRepository.findByRatingStartsWith("PG"); + assertEquals(6, results.size()); + } + + @Test + public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() { + List results = movieRepository.findByDirectorEndsWith("Burton"); + assertEquals(1, results.size()); + } + + @Test + public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() { + List results = movieRepository.findByTitleContainingIgnoreCase("the"); + assertEquals(2, results.size()); + } + + @Test + public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() { + List results = movieRepository.searchByTitleLike("in"); + assertEquals(3, results.size()); + } + + @Test + public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() { + List results = movieRepository.searchByRatingStartsWith("PG"); + assertEquals(6, results.size()); + } + + @Test + public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() { + List results = movieRepository.searchByDirectorEndsWith("Burton"); + assertEquals(1, results.size()); + } + + @Test + public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() { + List results = movieRepository.findByRatingNotContaining("PG"); + assertEquals(1, results.size()); + } + + @Test + public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() { + List results = movieRepository.findByDirectorNotLike("An%"); + assertEquals(5, results.size()); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java new file mode 100644 index 0000000000..4d3661e717 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.repository; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +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 com.baeldung.entity.Fruit; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class FruitPopulatorIntegrationTest { + + @Autowired + private FruitRepository fruitRepository; + + @Test + public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() { + + List fruits = fruitRepository.findAll(); + assertEquals("record count is not matching", 2, fruits.size()); + + fruits.forEach(fruit -> { + if (1 == fruit.getId()) { + assertEquals("apple", fruit.getName()); + assertEquals("red", fruit.getColor()); + } else if (2 == fruit.getId()) { + assertEquals("guava", fruit.getName()); + assertEquals("green", fruit.getColor()); + } + }); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java new file mode 100644 index 0000000000..37fcef7dab --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java @@ -0,0 +1,56 @@ +package com.baeldung.repository; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.core.IsNot.not; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.entity.Passenger; + +@DataJpaTest +@RunWith(SpringRunner.class) +public class PassengerRepositoryIntegrationTest { + + @PersistenceContext + private EntityManager entityManager; + @Autowired + private PassengerRepository repository; + + @Before + public void before() { + entityManager.persist(Passenger.from("Jill", "Smith")); + entityManager.persist(Passenger.from("Eve", "Jackson")); + entityManager.persist(Passenger.from("Fred", "Bloggs")); + entityManager.persist(Passenger.from("Ricki", "Bobbie")); + entityManager.persist(Passenger.from("Siya", "Kolisi")); + } + + @Test + public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { + Passenger jill = Passenger.from("Jill", "Smith"); + Passenger eve = Passenger.from("Eve", "Jackson"); + Passenger fred = Passenger.from("Fred", "Bloggs"); + Passenger siya = Passenger.from("Siya", "Kolisi"); + Passenger ricki = Passenger.from("Ricki", "Bobbie"); + + List passengers = repository.findByFirstNameIgnoreCase("FRED"); + + assertThat(passengers, contains(fred)); + assertThat(passengers, not(contains(eve))); + assertThat(passengers, not(contains(siya))); + assertThat(passengers, not(contains(jill))); + assertThat(passengers, not(contains(ricki))); + + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java new file mode 100644 index 0000000000..19362acd44 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java @@ -0,0 +1,59 @@ +package com.baeldung.repository; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +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.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.entity.Song; +import com.baeldung.repository.SongRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest +@Sql(scripts = { "/test-song-data.sql" }) +public class SongRepositoryIntegrationTest { + + @Autowired private SongRepository songRepository; + + @Transactional + @Test + public void givenSong_WhenFindLikeByName_ThenShouldReturnOne() { + List songs = songRepository.findByNameLike("Despacito"); + assertEquals(1, songs.size()); + } + + @Transactional + @Test + public void givenSong_WhenFindByNameNotLike_thenShouldReturn3Songs() { + List songs = songRepository.findByNameNotLike("Despacito"); + assertEquals(5, songs.size()); + } + + @Transactional + @Test + public void givenSong_WhenFindByNameStartingWith_thenShouldReturn2Songs() { + List songs = songRepository.findByNameStartingWith("Co"); + assertEquals(2, songs.size()); + } + + @Transactional + @Test + public void givenSong_WhenFindByNameEndingWith_thenShouldReturn2Songs() { + List songs = songRepository.findByNameEndingWith("Life"); + assertEquals(2, songs.size()); + } + + @Transactional + @Test + public void givenSong_WhenFindBySingerContaining_thenShouldReturn2Songs() { + List songs = songRepository.findBySingerContaining("Luis"); + assertEquals(2, songs.size()); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties new file mode 100644 index 0000000000..f9497c8f37 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +spring.jpa.hibernate.ddl-auto=update +spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql new file mode 100644 index 0000000000..90aa15307c --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-cleanup.sql @@ -0,0 +1 @@ +DELETE FROM Movie; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql new file mode 100644 index 0000000000..37f8e4fe64 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-movie-data.sql @@ -0,0 +1,7 @@ +INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); +INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); +INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); +INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); +INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); +INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); +INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); diff --git a/persistence-modules/spring-data-jpa-repo/src/test/resources/test-song-data.sql b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-song-data.sql new file mode 100644 index 0000000000..5a2b1a5555 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/test/resources/test-song-data.sql @@ -0,0 +1,8 @@ +INSERT INTO song(id,name,length_in_seconds,compositor,singer,released,genre) +VALUES +(1,'Despacito',209,'Luis Fonsi','Luis Fonsi, Daddy Yankee','2017-01-12','Reggaeton'), +(2,'Con calma',188,'Daddy Yankee','Daddy Yankee','2019-01-24','Reggaeton'), +(3,'It''s My Life',205,'Bon Jovi','Jon Bon Jovi','2000-05-23','Pop'), +(4,'Live is Life',242,'Opus','Opus','1985-01-01','Reggae'), +(5,'Countdown to Extinction',249,'Megadeth','Megadeth','1992-07-14','Heavy Metal'), +(6, 'Si nos dejan',139,'Luis Miguel','Luis Miguel','1995-10-17','Bolero'); \ No newline at end of file From 3bebbd4c0295740c95e6e75e17023154001bd2af Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:32:35 +0530 Subject: [PATCH 057/155] JAVA-66: removed old modules spring-data-jpa-* --- .../spring-data-jpa-2/README.md | 12 - persistence-modules/spring-data-jpa-2/pom.xml | 48 -- .../main/java/com/baeldung/Application.java | 13 - .../baeldung/aggregation/model/Comment.java | 85 --- .../com/baeldung/aggregation/model/Post.java | 75 --- .../model/custom/CommentCount.java | 27 - .../model/custom/ICommentCount.java | 8 - .../repository/CommentRepository.java | 27 - .../com/baeldung/config/JpaPopulators.java | 35 -- .../baeldung/datajpadelete/entity/Book.java | 51 -- .../datajpadelete/entity/Category.java | 60 -- .../repository/BookRepository.java | 19 - .../repository/CategoryRepository.java | 9 - .../baeldung/embeddable/model/Company.java | 71 --- .../embeddable/model/ContactPerson.java | 38 -- .../repositories/CompanyRepository.java | 18 - .../java/com/baeldung/entity/Customer.java | 37 -- .../main/java/com/baeldung/entity/Fruit.java | 40 -- .../java/com/baeldung/entity/Passenger.java | 78 --- .../main/java/com/baeldung/entity/Song.java | 75 --- .../entitygraph/model/Characteristic.java | 43 -- .../com/baeldung/entitygraph/model/Item.java | 48 -- .../repository/CharacteristicsRepository.java | 13 - .../repository/ItemRepository.java | 13 - .../main/java/com/baeldung/exists/Car.java | 48 -- .../com/baeldung/exists/CarRepository.java | 24 - .../com/baeldung/joins/model/Department.java | 45 -- .../com/baeldung/joins/model/Employee.java | 69 --- .../java/com/baeldung/joins/model/Phone.java | 44 -- .../baeldung/projection/model/Address.java | 57 -- .../com/baeldung/projection/model/Person.java | 47 -- .../repository/AddressRepository.java | 11 - .../repository/PersonRepository.java | 14 - .../baeldung/projection/view/AddressView.java | 7 - .../baeldung/projection/view/PersonDto.java | 34 -- .../baeldung/projection/view/PersonView.java | 12 - .../repository/CustomerRepository.java | 19 - .../baeldung/repository/FruitRepository.java | 27 - .../repository/PassengerRepository.java | 14 - .../baeldung/repository/SongRepository.java | 21 - .../src/main/resources/apple-fruit-data.xml | 7 - .../resources/application-joins.properties | 1 - .../src/main/resources/application.properties | 1 - .../src/main/resources/db/import_joins.sql | 13 - .../src/main/resources/fruit-data.json | 14 - .../src/main/resources/guava-fruit-data.xml | 7 - .../SpringDataAggregateIntegrationTest.java | 107 ---- .../DeleteFromRepositoryUnitTest.java | 72 --- .../DeleteInRelationshipsUnitTest.java | 60 -- .../embeddable/EmbeddableIntegrationTest.java | 125 ---- .../EntityGraphIntegrationTest.java | 39 -- .../exists/CarRepositoryIntegrationTest.java | 87 --- .../joins/JpaJoinsIntegrationTest.java | 142 ----- .../JpaProjectionIntegrationTest.java | 63 -- .../CustomerRepositoryIntegrationTest.java | 64 -- .../FruitPopulatorIntegrationTest.java | 38 -- .../FruitRepositoryIntegrationTest.java | 75 --- .../PassengerRepositoryIntegrationTest.java | 54 -- .../SongRepositoryIntegrationTest.java | 58 -- .../src/test/resources/entitygraph-data.sql | 7 - .../resources/projection-clean-up-data.sql | 2 - .../test/resources/projection-insert-data.sql | 2 - .../test/resources/test-aggregation-data.sql | 7 - .../src/test/resources/test-fruit-data.sql | 6 - .../src/test/resources/test-song-data.sql | 8 - .../spring-data-jpa-3/README.md | 20 - persistence-modules/spring-data-jpa-3/pom.xml | 71 --- .../main/java/com/baeldung/Application.java | 14 - .../DatasourceProxyBeanPostProcessor.java | 53 -- .../baeldung/batchinserts/model/School.java | 45 -- .../baeldung/batchinserts/model/Student.java | 44 -- .../java/com/baeldung/boot/Application.java | 17 - .../boot/daos/CustomerRepository.java | 19 - .../daos/impl/PersonInsertRepository.java | 31 - .../boot/daos/user/UserRepository.java | 99 ---- .../boot/daos/user/UserRepositoryCustom.java | 14 - .../daos/user/UserRepositoryCustomImpl.java | 57 -- .../com/baeldung/boot/domain/Customer.java | 56 -- .../java/com/baeldung/boot/domain/Person.java | 47 -- .../com/baeldung/boot/domain/Possession.java | 83 --- .../java/com/baeldung/boot/domain/User.java | 132 ----- .../passenger/CustomPassengerRepository.java | 8 - .../baeldung/boot/passenger/Passenger.java | 82 --- .../boot/passenger/PassengerRepository.java | 22 - .../passenger/PassengerRepositoryImpl.java | 20 - .../web/controllers/CustomerController.java | 41 -- .../java/com/baeldung/entity/Employee.java | 36 -- .../java/com/baeldung/model/BasicUser.java | 42 -- .../multipledb/MultipleDbApplication.java | 14 - .../PersistenceProductConfiguration.java | 68 --- .../dao/product/ProductRepository.java | 13 - .../multipledb/model/product/Product.java | 67 --- .../repository/EmployeeRepository.java | 9 - .../baeldung/repository/UserRepository.java | 14 - .../src/main/resources/application.properties | 6 - .../src/main/resources/logback.xml | 13 - .../persistence-multiple-db.properties | 13 - .../java/com/baeldung/SpringContextTest.java | 17 - .../SpringJpaContextIntegrationTest.java | 19 - .../BatchInsertIntegrationTest.java | 40 -- .../JpaBatchInsertsIntegrationTest.java | 98 ---- .../JpaNoBatchInsertsIntegrationTest.java | 41 -- .../batchinserts/TestObjectHelper.java | 20 - ...PersonInsertRepositoryIntegrationTest.java | 82 --- .../boot/daos/UserRepositoryCommon.java | 545 ------------------ .../daos/UserRepositoryTCAutoLiveTest.java | 43 -- .../boot/daos/UserRepositoryTCLiveTest.java | 58 -- .../PassengerRepositoryIntegrationTest.java | 190 ------ .../ProductRepositoryIntegrationTest.java | 142 ----- .../EmployeeRepositoryIntegrationTest.java | 40 -- .../util/BaeldungPostgresqlContainer.java | 35 -- .../application-batchinserts.properties | 6 - .../resources/application-tc-auto.properties | 4 - .../test/resources/application-tc.properties | 4 - .../resources/application-test.properties | 2 - .../spring-data-jpa-4/README.md | 18 - .../spring-data-jpa-4/create.sql | 2 - persistence-modules/spring-data-jpa-4/pom.xml | 47 -- .../derivedquery/QueryApplication.java | 13 - .../baeldung/derivedquery/entity/User.java | 70 --- .../repository/UserRepository.java | 60 -- .../ElementCollectionApplication.java | 11 - .../elementcollection/model/Employee.java | 68 --- .../elementcollection/model/Phone.java | 62 -- .../repository/EmployeeRepository.java | 46 -- .../SpringBootLifecycleEventApplication.java | 11 - .../model/AuditTrailListener.java | 39 -- .../baeldung/lifecycleevents/model/User.java | 104 ---- .../repository/UserRepository.java | 9 - .../com/baeldung/like/LikeApplication.java | 13 - .../java/com/baeldung/like/model/Movie.java | 58 -- .../like/repository/MovieRepository.java | 41 -- .../com/baeldung/namingstrategy/Person.java | 35 -- .../namingstrategy/PersonRepository.java | 6 - .../QuotedLowerCaseNamingStrategy.java | 12 - .../QuotedUpperCaseNamingStrategy.java | 12 - ...ingDataJpaNamingConventionApplication.java | 7 - .../UnquotedLowerCaseNamingStrategy.java | 12 - .../UnquotedUpperCaseNamingStrategy.java | 12 - .../com/baeldung/osiv/OsivApplication.java | 13 - .../com/baeldung/osiv/model/BasicUser.java | 42 -- .../osiv/repository/BasicUserRepository.java | 19 - .../osiv/service/SimpleUserService.java | 25 - .../baeldung/osiv/service/UserService.java | 9 - .../baeldung/osiv/web/DetailedUserDto.java | 45 -- .../com/baeldung/osiv/web/UserController.java | 27 - .../StoredProcedureApplication.java | 13 - .../controller/CarController.java | 47 -- .../baeldung/storedprocedure/entity/Car.java | 41 -- .../repository/CarRepository.java | 34 -- .../storedprocedure/service/CarService.java | 39 -- .../java/com/baeldung/tx/TxApplication.java | 13 - .../java/com/baeldung/tx/model/Payment.java | 55 -- .../src/main/resources/application.properties | 5 - .../src/main/resources/car-mysql.sql | 27 - .../UserRepositoryIntegrationTest.java | 172 ------ .../ElementCollectionIntegrationTest.java | 64 -- .../like/MovieRepositoryIntegrationTest.java | 87 --- ...erCaseNamingStrategyH2IntegrationTest.java | 81 --- ...werCaseNamingStrategyPostgresLiveTest.java | 85 --- ...erCaseNamingStrategyH2IntegrationTest.java | 85 --- ...perCaseNamingStrategyPostgresLiveTest.java | 81 --- ...ysicalNamingStrategyH2IntegrationTest.java | 85 --- ...hysicalNamingStrategyPostgresLiveTest.java | 85 --- ...erCaseNamingStrategyH2IntegrationTest.java | 86 --- ...werCaseNamingStrategyPostgresLiveTest.java | 85 --- ...erCaseNamingStrategyH2IntegrationTest.java | 85 --- ...perCaseNamingStrategyPostgresLiveTest.java | 85 --- .../osiv/UserControllerIntegrationTest.java | 56 -- .../tx/ManualTransactionIntegrationTest.java | 152 ----- .../UserRepositoryIntegrationTest.java | 80 --- .../resources/application-test.properties | 2 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-lower-case-naming-strategy.properties | 9 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-upper-case-naming-strategy.properties | 9 - ...cal-naming-strategy-on-postgres.properties | 9 - ...spring-physical-naming-strategy.properties | 9 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-lower-case-naming-strategy.properties | 9 - ...ase-naming-strategy-on-postgres.properties | 9 - ...oted-upper-case-naming-strategy.properties | 9 - .../src/test/resources/test-movie-cleanup.sql | 1 - .../src/test/resources/test-movie-data.sql | 7 - .../spring-data-jpa-5/README.md | 15 - persistence-modules/spring-data-jpa-5/pom.xml | 80 --- .../baeldung/composite/BookApplication.java | 12 - .../com/baeldung/composite/entity/Book.java | 47 -- .../com/baeldung/composite/entity/BookId.java | 51 -- .../composite/repository/BookRepository.java | 18 - .../PartialUpdateApplication.java | 12 - .../partialupdate/model/ContactPhone.java | 22 - .../partialupdate/model/Customer.java | 23 - .../partialupdate/model/CustomerDto.java | 31 - .../model/CustomerStructured.java | 27 - .../repository/ContactPhoneRepository.java | 12 - .../repository/CustomerRepository.java | 18 - .../CustomerStructuredRepository.java | 11 - .../service/CustomerService.java | 87 --- .../partialupdate/util/CustomerMapper.java | 15 - .../schemageneration/AccountApplication.java | 12 - .../schemageneration/HibernateUtil.java | 39 -- .../schemageneration/model/Account.java | 74 --- .../model/AccountSetting.java | 68 --- .../repository/AccountRepository.java | 8 - .../repository/AccountSettingRepository.java | 8 - .../src/main/resources/application.properties | 13 - .../BookRepositoryIntegrationTest.java | 64 -- .../partialupdate/PartialUpdateUnitTest.java | 63 -- .../AccountRepositoryIntegrationTest.java | 72 --- .../resources/application-test.properties | 3 - persistence-modules/spring-data-jpa/README.md | 25 - persistence-modules/spring-data-jpa/pom.xml | 77 --- .../java/com/baeldung/boot/Application.java | 17 - .../boot/config/PersistenceConfiguration.java | 23 - .../baeldung/boot/daos/ArticleRepository.java | 23 - .../boot/daos/CustomItemRepository.java | 16 - .../boot/daos/CustomItemTypeRepository.java | 13 - .../boot/daos/ExtendedRepository.java | 14 - .../boot/daos/ExtendedStudentRepository.java | 6 - .../boot/daos/IBarCrudRepository.java | 11 - .../java/com/baeldung/boot/daos/IFooDao.java | 13 - .../boot/daos/InventoryRepository.java | 8 - .../boot/daos/ItemTypeRepository.java | 10 - .../boot/daos/LocationRepository.java | 10 - .../boot/daos/ReadOnlyLocationRepository.java | 15 - .../baeldung/boot/daos/StoreRepository.java | 13 - .../daos/impl/CustomItemRepositoryImpl.java | 33 -- .../impl/CustomItemTypeRepositoryImpl.java | 27 - .../daos/impl/ExtendedRepositoryImpl.java | 37 -- .../boot/daos/user/PossessionRepository.java | 9 - .../boot/daos/user/UserRepository.java | 99 ---- .../boot/daos/user/UserRepositoryCustom.java | 14 - .../daos/user/UserRepositoryCustomImpl.java | 57 -- .../baeldung/boot/ddd/event/Aggregate.java | 46 -- .../baeldung/boot/ddd/event/Aggregate2.java | 44 -- .../boot/ddd/event/Aggregate2Repository.java | 10 - .../baeldung/boot/ddd/event/Aggregate3.java | 23 - .../boot/ddd/event/Aggregate3Repository.java | 14 - .../boot/ddd/event/AggregateRepository.java | 10 - .../baeldung/boot/ddd/event/DddConfig.java | 15 - .../baeldung/boot/ddd/event/DomainEvent.java | 8 - .../boot/ddd/event/DomainService.java | 31 - .../com/baeldung/boot/domain/Article.java | 23 - .../java/com/baeldung/boot/domain/Bar.java | 220 ------- .../java/com/baeldung/boot/domain/Foo.java | 94 --- .../java/com/baeldung/boot/domain/Item.java | 81 --- .../com/baeldung/boot/domain/ItemType.java | 46 -- .../java/com/baeldung/boot/domain/KVTag.java | 34 -- .../com/baeldung/boot/domain/Location.java | 55 -- .../boot/domain/MerchandiseEntity.java | 66 --- .../com/baeldung/boot/domain/Possession.java | 83 --- .../com/baeldung/boot/domain/SkillTag.java | 30 - .../java/com/baeldung/boot/domain/Store.java | 76 --- .../com/baeldung/boot/domain/Student.java | 74 --- .../java/com/baeldung/boot/domain/User.java | 132 ----- .../baeldung/boot/services/IBarService.java | 7 - .../baeldung/boot/services/IFooService.java | 14 - .../baeldung/boot/services/IOperations.java | 26 - .../boot/services/impl/AbstractService.java | 61 -- .../impl/AbstractSpringDataJpaService.java | 45 -- .../impl/BarSpringDataJpaService.java | 31 - .../boot/services/impl/FooService.java | 55 -- .../multipledb/MultipleDbApplication.java | 14 - .../PersistenceProductAutoConfiguration.java | 71 --- .../PersistenceProductConfiguration.java | 68 --- .../PersistenceUserAutoConfiguration.java | 75 --- .../PersistenceUserConfiguration.java | 69 --- .../dao/product/ProductRepository.java | 14 - .../dao/user/PossessionRepository.java | 9 - .../multipledb/dao/user/UserRepository.java | 8 - .../multipledb/model/product/Product.java | 67 --- .../model/user/PossessionMultipleDB.java | 82 --- .../multipledb/model/user/UserMultipleDB.java | 88 --- .../src/main/resources/application.properties | 6 - .../src/main/resources/ddd.properties | 1 - .../src/main/resources/import_entities.sql | 21 - .../src/main/resources/logback.xml | 13 - .../persistence-multiple-db-boot.properties | 11 - .../persistence-multiple-db.properties | 13 - .../src/main/resources/persistence.properties | 14 - .../java/com/baeldung/SpringContextTest.java | 17 - .../SpringJpaContextIntegrationTest.java | 25 - .../ArticleRepositoryIntegrationTest.java | 67 --- ...endedStudentRepositoryIntegrationTest.java | 41 -- .../InventoryRepositoryIntegrationTest.java | 61 -- .../daos/JpaRepositoriesIntegrationTest.java | 93 --- .../boot/daos/UserRepositoryCommon.java | 545 ------------------ .../daos/UserRepositoryIntegrationTest.java | 37 -- .../daos/UserRepositoryTCAutoLiveTest.java | 43 -- .../boot/daos/UserRepositoryTCLiveTest.java | 58 -- .../Aggregate2EventsIntegrationTest.java | 72 --- .../Aggregate3EventsIntegrationTest.java | 67 --- .../event/AggregateEventsIntegrationTest.java | 87 --- .../boot/ddd/event/TestEventHandler.java | 14 - ...ractServicePersistenceIntegrationTest.java | 252 -------- .../FooServicePersistenceIntegrationTest.java | 75 --- .../SpringDataJPABarAuditIntegrationTest.java | 75 --- .../JpaMultipleDBIntegrationTest.java | 96 --- .../ProductRepositoryIntegrationTest.java | 144 ----- .../util/BaeldungPostgresqlContainer.java | 35 -- .../test/java/com/baeldung/util/IDUtil.java | 33 -- .../resources/application-tc-auto.properties | 4 - .../test/resources/application-tc.properties | 4 - 304 files changed, 13445 deletions(-) delete mode 100644 persistence-modules/spring-data-jpa-2/README.md delete mode 100644 persistence-modules/spring-data-jpa-2/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json delete mode 100644 persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql delete mode 100644 persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql delete mode 100644 persistence-modules/spring-data-jpa-3/README.md delete mode 100644 persistence-modules/spring-data-jpa-3/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml delete mode 100644 persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties delete mode 100644 persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties delete mode 100644 persistence-modules/spring-data-jpa-4/README.md delete mode 100644 persistence-modules/spring-data-jpa-4/create.sql delete mode 100644 persistence-modules/spring-data-jpa-4/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql delete mode 100644 persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql delete mode 100644 persistence-modules/spring-data-jpa-5/README.md delete mode 100644 persistence-modules/spring-data-jpa-5/pom.xml delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties delete mode 100644 persistence-modules/spring-data-jpa/README.md delete mode 100644 persistence-modules/spring-data-jpa/pom.xml delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java delete mode 100755 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java delete mode 100755 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/application.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/ddd.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/logback.xml delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties delete mode 100644 persistence-modules/spring-data-jpa/src/main/resources/persistence.properties delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java delete mode 100644 persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties delete mode 100644 persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties diff --git a/persistence-modules/spring-data-jpa-2/README.md b/persistence-modules/spring-data-jpa-2/README.md deleted file mode 100644 index e59aca7c69..0000000000 --- a/persistence-modules/spring-data-jpa-2/README.md +++ /dev/null @@ -1,12 +0,0 @@ -### Relevant Articles: -- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby) -- [JPA Join Types](https://www.baeldung.com/jpa-join-types) -- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) -- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) -- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators) -- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) -- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) -- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable) -- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete) -- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs) -- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) diff --git a/persistence-modules/spring-data-jpa-2/pom.xml b/persistence-modules/spring-data-jpa-2/pom.xml deleted file mode 100644 index 838327de89..0000000000 --- a/persistence-modules/spring-data-jpa-2/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - 4.0.0 - spring-data-jpa-2 - spring-data-jpa-2 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.h2database - h2 - - - - net.ttddyy - datasource-proxy - ${datasource-proxy.version} - - - - com.fasterxml.jackson.core - jackson-databind - - - - org.springframework - spring-oxm - - - - - 1.4.1 - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java deleted file mode 100644 index 3ea3d113da..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java deleted file mode 100644 index 26c2373cbe..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Comment.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.aggregation.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import java.util.Objects; - -@Entity -public class Comment { - @Id - private Integer id; - private Integer year; - private boolean approved; - private String content; - @ManyToOne - private Post post; - - public Comment() { - } - - public Comment(int id, int year, boolean approved, String content, Post post) { - this.id = id; - this.year = year; - this.approved = approved; - this.content = content; - this.post = post; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - public boolean isApproved() { - return approved; - } - - public void setApproved(boolean approved) { - this.approved = approved; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public Post getPost() { - return post; - } - - public void setPost(Post post) { - this.post = post; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Comment)) { - return false; - } - Comment comment = (Comment) o; - return getId().equals(comment.getId()); - } - - @Override - public int hashCode() { - return Objects.hash(getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java deleted file mode 100644 index f396e080ae..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/Post.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.aggregation.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import java.util.List; -import java.util.Objects; - -@Entity -public class Post { - @Id - private Integer id; - private String title; - private String content; - @OneToMany(mappedBy = "post") - private List comments; - - public Post() { - } - - public Post(Integer id, String title, String content) { - this.id = id; - this.title = title; - this.content = content; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getContent() { - return content; - } - - public void setContent(String content) { - this.content = content; - } - - public List getComments() { - return comments; - } - - public void setComments(List comments) { - this.comments = comments; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Post)) { - return false; - } - Post post = (Post) o; - return getId().equals(post.getId()); - } - - @Override - public int hashCode() { - return Objects.hash(getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java deleted file mode 100644 index 510b52a47c..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.aggregation.model.custom; - -public class CommentCount { - private Integer year; - private Long total; - - public CommentCount(Integer year, Long total) { - this.year = year; - this.total = total; - } - - public Integer getYear() { - return year; - } - - public void setYear(Integer year) { - this.year = year; - } - - public Long getTotal() { - return total; - } - - public void setTotal(Long total) { - this.total = total; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java deleted file mode 100644 index acb25cfd49..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.aggregation.model.custom; - -public interface ICommentCount { - - Integer getYearComment(); - - Long getTotalComment(); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java deleted file mode 100644 index 89e9345e94..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.aggregation.repository; - -import com.baeldung.aggregation.model.Comment; -import com.baeldung.aggregation.model.custom.CommentCount; -import com.baeldung.aggregation.model.custom.ICommentCount; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface CommentRepository extends JpaRepository { - - @Query("SELECT c.year, COUNT(c.year) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") - List countTotalCommentsByYear(); - - @Query("SELECT new com.baeldung.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") - List countTotalCommentsByYearClass(); - - @Query("SELECT c.year AS yearComment, COUNT(c.year) AS totalComment FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") - List countTotalCommentsByYearInterface(); - - @Query(value = "SELECT c.year AS yearComment, COUNT(c.*) AS totalComment FROM comment AS c GROUP BY c.year ORDER BY c.year DESC", nativeQuery = true) - List countTotalCommentsByYearNative(); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java deleted file mode 100644 index 24348d31c5..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/config/JpaPopulators.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean; -import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; - -import com.baeldung.entity.Fruit; - -@Configuration -public class JpaPopulators { - - @Bean - public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception { - Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean(); - factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") }); - return factory; - } - - @Bean - public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() { - - Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller(); - unmarshaller.setClassesToBeBound(Fruit.class); - - UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean(); - factory.setUnmarshaller(unmarshaller); - factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") }); - return factory; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java deleted file mode 100644 index deac24548a..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Book.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.datajpadelete.entity; - -import javax.persistence.*; - -@Entity -public class Book { - - @Id - @GeneratedValue - private Long id; - private String title; - - @ManyToOne - private Category category; - - public Book() { - } - - public Book(String title) { - this.title = title; - } - - public Book(String title, Category category) { - this.title = title; - this.category = category; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public Category getCategory() { - return category; - } - - public void setCategory(Category category) { - this.category = category; - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java deleted file mode 100644 index 16f1a4157f..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/entity/Category.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.datajpadelete.entity; - -import javax.persistence.*; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -@Entity -public class Category { - - @Id - @GeneratedValue - private Long id; - private String name; - - @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true) - private List books; - - public Category() { - } - - public Category(String name) { - this.name = name; - } - - public Category(String name, Book... books) { - this.name = name; - this.books = Stream.of(books).collect(Collectors.toList()); - this.books.forEach(x -> x.setCategory(this)); - } - - public Category(String name, List books) { - this.name = name; - this.books = books; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getBooks() { - return books; - } - - public void setBooks(List books) { - this.books = books; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java deleted file mode 100644 index 5d0f45f127..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/BookRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.datajpadelete.repository; - -import com.baeldung.datajpadelete.entity.Book; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -@Repository -public interface BookRepository extends CrudRepository { - - long deleteByTitle(String title); - - @Modifying - @Query("delete from Book b where b.title=:title") - void deleteBooks(@Param("title") String title); - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java deleted file mode 100644 index 6fe7058a78..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/datajpadelete/repository/CategoryRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.datajpadelete.repository; - -import com.baeldung.datajpadelete.entity.Category; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface CategoryRepository extends CrudRepository { -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java deleted file mode 100644 index 203cff1e35..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/Company.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.embeddable.model; - -import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Company { - - @Id - @GeneratedValue - private Integer id; - - private String name; - - private String address; - - private String phone; - - @Embedded - @AttributeOverrides(value = { - @AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")), - @AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name")), - @AttributeOverride( name = "phone", column = @Column(name = "contact_phone")) - }) - private ContactPerson contactPerson; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public ContactPerson getContactPerson() { - return contactPerson; - } - - public void setContactPerson(ContactPerson contactPerson) { - this.contactPerson = contactPerson; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java deleted file mode 100644 index 561da80878..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/model/ContactPerson.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.embeddable.model; - -import javax.persistence.Embeddable; - -@Embeddable -public class ContactPerson { - - private String firstName; - - private String lastName; - - private String phone; - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java deleted file mode 100644 index f456b15652..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/embeddable/repositories/CompanyRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.embeddable.repositories; - -import com.baeldung.embeddable.model.Company; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - -import java.util.List; - -public interface CompanyRepository extends JpaRepository { - - List findByContactPersonFirstName(String firstName); - - @Query("SELECT C FROM Company C WHERE C.contactPerson.firstName = ?1") - List findByContactPersonFirstNameWithJPQL(String firstName); - - @Query(value = "SELECT * FROM company WHERE contact_first_name = ?1", nativeQuery = true) - List findByContactPersonFirstNameWithNativeQuery(String firstName); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java deleted file mode 100644 index efcae73853..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Customer.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -@Entity -public class Customer { - - @Id - @GeneratedValue - private long id; - private String name; - private String email; - - public Customer(String name, String email) { - this.name = name; - this.email = email; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java deleted file mode 100644 index d45ac33db8..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Fruit.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@Entity -public class Fruit { - - @Id - private long id; - private String name; - private String color; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java deleted file mode 100644 index 3aafbe9afa..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Passenger.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Basic; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import java.util.Objects; - -@Entity -public class Passenger { - - @Id - @GeneratedValue - @Column(nullable = false) - private Long id; - - @Basic(optional = false) - @Column(nullable = false) - private String firstName; - - @Basic(optional = false) - @Column(nullable = false) - private String lastName; - - private Passenger(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public static Passenger from(String firstName, String lastName) { - return new Passenger(firstName, lastName); - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - @Override - public String toString() { - return "Passenger{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Passenger passenger = (Passenger) o; - return Objects.equals(firstName, passenger.firstName) && Objects.equals(lastName, passenger.lastName); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java deleted file mode 100644 index 395527c1eb..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entity/Song.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import java.time.LocalDateTime; - -@Entity -public class Song { - - @Id private long id; - private String name; - @Column(name = "length_in_seconds") - private int lengthInSeconds; - private String compositor; - private String singer; - private LocalDateTime released; - private String genre; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getLengthInSeconds() { - return lengthInSeconds; - } - - public void setLengthInSeconds(int lengthInSeconds) { - this.lengthInSeconds = lengthInSeconds; - } - - public String getCompositor() { - return compositor; - } - - public void setCompositor(String compositor) { - this.compositor = compositor; - } - - public String getSinger() { - return singer; - } - - public void setSinger(String singer) { - this.singer = singer; - } - - public LocalDateTime getReleased() { - return released; - } - - public void setReleased(LocalDateTime released) { - this.released = released; - } - - public String getGenre() { - return genre; - } - - public void setGenre(String genre) { - this.genre = genre; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java deleted file mode 100644 index ae20375572..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Characteristic.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.entitygraph.model; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -@Entity -public class Characteristic { - - @Id - private Long id; - private String type; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn - private Item item; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Item getItem() { - return item; - } - - public void setItem(Item item) { - this.item = item; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java deleted file mode 100644 index e90a22ef62..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/model/Item.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.entitygraph.model; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedAttributeNode; -import javax.persistence.NamedEntityGraph; -import javax.persistence.OneToMany; - -@Entity -@NamedEntityGraph(name = "Item.characteristics", - attributeNodes = @NamedAttributeNode("characteristics") -) -public class Item { - - @Id - private Long id; - private String name; - - @OneToMany(mappedBy = "item") - private List characteristics = new ArrayList<>(); - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getCharacteristics() { - return characteristics; - } - - public void setCharacteristics(List characteristics) { - this.characteristics = characteristics; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java deleted file mode 100644 index 9f923ab241..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/CharacteristicsRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.entitygraph.repository; - -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.entitygraph.model.Characteristic; - -public interface CharacteristicsRepository extends JpaRepository { - - @EntityGraph(attributePaths = {"item"}) - Characteristic findByType(String type); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java deleted file mode 100644 index b2a5f223b3..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/entitygraph/repository/ItemRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.entitygraph.repository; - -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.entitygraph.model.Item; - -public interface ItemRepository extends JpaRepository { - - @EntityGraph(value = "Item.characteristics", type = EntityGraphType.FETCH) - Item findByName(String name); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java deleted file mode 100644 index bf09caf6ff..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/Car.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.exists; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -/** - * @author paullatzelsperger - * @since 2019-03-20 - */ -@Entity -public class Car { - - @Id - @GeneratedValue - private int id; - private Integer power; - private String model; - - Car() { - - } - - public Car(int power, String model) { - this.power = power; - this.model = model; - } - - public Integer getPower() { - return power; - } - - public void setPower(Integer power) { - this.power = power; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } - - public int getId() { - return id; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java deleted file mode 100644 index a54f19f4cd..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/exists/CarRepository.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.exists; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -/** - * @author paullatzelsperger - * @since 2019-03-20 - */ -@Repository -public interface CarRepository extends JpaRepository { - - boolean existsCarByPower(int power); - - boolean existsCarByModel(String model); - - @Query("select case when count(c)> 0 then true else false end from Car c where c.model = :model") - boolean existsCarExactCustomQuery(@Param("model") String model); - - @Query("select case when count(c)> 0 then true else false end from Car c where lower(c.model) like lower(:model)") - boolean existsCarLikeCustomQuery(@Param("model") String model); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java deleted file mode 100644 index 439f7532f5..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Department.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.joins.model; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class Department { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - private String name; - - @OneToMany(mappedBy = "department") - private List employees; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getEmployees() { - return employees; - } - - public void setEmployees(List employees) { - this.employees = employees; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java deleted file mode 100644 index 277274e61c..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Employee.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.joins.model; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.Table; - -@Entity -@Table(name = "joins_employee") -public class Employee { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - private int age; - - @ManyToOne - private Department department; - - @OneToMany(mappedBy = "employee") - private List phones; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public Department getDepartment() { - return department; - } - - public void setDepartment(Department department) { - this.department = department; - } - - public List getPhones() { - return phones; - } - - public void setPhones(List phones) { - this.phones = phones; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java deleted file mode 100644 index 41382915b1..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/joins/model/Phone.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.joins.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class Phone { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String number; - - @ManyToOne - private Employee employee; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - public Employee getEmployee() { - return employee; - } - - public void setEmployee(Employee employee) { - this.employee = employee; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java deleted file mode 100644 index 0c5a3eac60..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Address.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.projection.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -@Entity -public class Address { - @Id - private Long id; - @OneToOne - private Person person; - private String state; - private String city; - private String street; - private String zipCode; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getState() { - return state; - } - - public void setState(String state) { - this.state = state; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getZipCode() { - return zipCode; - } - - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java deleted file mode 100644 index d18bd1c72d..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/model/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.projection.model; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; - -@Entity -public class Person { - @Id - private Long id; - private String firstName; - private String lastName; - @OneToOne(mappedBy = "person") - private Address address; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java deleted file mode 100644 index c1053f4867..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/AddressRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.projection.repository; - -import com.baeldung.projection.view.AddressView; -import com.baeldung.projection.model.Address; -import org.springframework.data.repository.Repository; - -import java.util.List; - -public interface AddressRepository extends Repository { - List getAddressByState(String state); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java deleted file mode 100644 index 64bc7471e6..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/repository/PersonRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.projection.repository; - -import com.baeldung.projection.model.Person; -import com.baeldung.projection.view.PersonDto; -import com.baeldung.projection.view.PersonView; -import org.springframework.data.repository.Repository; - -public interface PersonRepository extends Repository { - PersonView findByLastName(String lastName); - - PersonDto findByFirstName(String firstName); - - T findByLastName(String lastName, Class type); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java deleted file mode 100644 index 7a24a1e9b9..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/AddressView.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.projection.view; - -public interface AddressView { - String getZipCode(); - - PersonView getPerson(); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java deleted file mode 100644 index 1fd924450b..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonDto.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.projection.view; - -import java.util.Objects; - -public class PersonDto { - private final String firstName; - private final String lastName; - - public PersonDto(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - PersonDto personDto = (PersonDto) o; - return Objects.equals(firstName, personDto.firstName) && Objects.equals(lastName, personDto.lastName); - } - - @Override - public int hashCode() { - return Objects.hash(firstName, lastName); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java deleted file mode 100644 index 36777ec26f..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/projection/view/PersonView.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.projection.view; - -import org.springframework.beans.factory.annotation.Value; - -public interface PersonView { - String getFirstName(); - - String getLastName(); - - @Value("#{target.firstName + ' ' + target.lastName}") - String getFullName(); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java deleted file mode 100644 index 65b22bbd84..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/CustomerRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Customer; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import java.util.List; - -public interface CustomerRepository extends JpaRepository { - - List findByName(String name); - - List findByNameAndEmail(String name, String email); - - @Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)") - List findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java deleted file mode 100644 index 5055252adf..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/FruitRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.baeldung.entity.Fruit; - -@Repository -public interface FruitRepository extends JpaRepository { - - Long deleteByName(String name); - - List deleteByColor(String color); - - Long removeByName(String name); - - List removeByColor(String color); - - @Modifying - @Query("delete from Fruit f where f.name=:name or f.color=:color") - int deleteFruits(@Param("name") String name, @Param("color") String color); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java deleted file mode 100644 index a295a74f1b..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/PassengerRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Passenger; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -interface PassengerRepository extends JpaRepository { - - List findByFirstNameIgnoreCase(String firstName); - -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java b/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java deleted file mode 100644 index ad887fe680..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/java/com/baeldung/repository/SongRepository.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Song; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface SongRepository extends JpaRepository { - - List findByNameLike(String name); - - List findByNameNotLike(String name); - - List findByNameStartingWith(String startingWith); - - List findByNameEndingWith(String endingWith); - - List findBySingerContaining(String singer); -} diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml b/persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml deleted file mode 100644 index d87ae28f1e..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/apple-fruit-data.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - 1 - apple - red - diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties b/persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties deleted file mode 100644 index fe2270293b..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/application-joins.properties +++ /dev/null @@ -1 +0,0 @@ -spring.datasource.data=classpath:db/import_joins.sql diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties deleted file mode 100644 index 72fc330767..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -spring.jpa.show-sql=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql b/persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql deleted file mode 100644 index e4772d6ff2..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/db/import_joins.sql +++ /dev/null @@ -1,13 +0,0 @@ -INSERT INTO department (id, name) VALUES (1, 'Infra'); -INSERT INTO department (id, name) VALUES (2, 'Accounting'); -INSERT INTO department (id, name) VALUES (3, 'Management'); - -INSERT INTO joins_employee (id, name, age, department_id) VALUES (1, 'Baeldung', '35', 1); -INSERT INTO joins_employee (id, name, age, department_id) VALUES (2, 'John', '35', 2); -INSERT INTO joins_employee (id, name, age, department_id) VALUES (3, 'Jane', '35', 2); - -INSERT INTO phone (id, number, employee_id) VALUES (1, '111', 1); -INSERT INTO phone (id, number, employee_id) VALUES (2, '222', 1); -INSERT INTO phone (id, number, employee_id) VALUES (3, '333', 1); - -COMMIT; diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json b/persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json deleted file mode 100644 index 6dc44e2586..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/fruit-data.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "_class": "com.baeldung.entity.Fruit", - "name": "apple", - "color": "red", - "id": 1 - }, - { - "_class": "com.baeldung.entity.Fruit", - "name": "guava", - "color": "green", - "id": 2 - } -] \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml b/persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml deleted file mode 100644 index ffd75bb4bb..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/main/resources/guava-fruit-data.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - 2 - guava - green - diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java deleted file mode 100644 index 779ade7a3f..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.baeldung.aggregation; - -import com.baeldung.aggregation.model.custom.CommentCount; -import com.baeldung.aggregation.model.custom.ICommentCount; -import com.baeldung.aggregation.repository.CommentRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.List; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -@RunWith(SpringRunner.class) -@DataJpaTest - -@Sql(scripts = "/test-aggregation-data.sql") -public class SpringDataAggregateIntegrationTest { - - @Autowired - private CommentRepository commentRepository; - - @Test - public void whenQueryWithAggregation_thenReturnResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYear(); - - Object[] countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019[0], is(Integer.valueOf(2019))); - assertThat(countYear2019[1], is(1l)); - - Object[] countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018[0], is(Integer.valueOf(2018))); - assertThat(countYear2018[1], is(2l)); - - Object[] countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017[0], is(Integer.valueOf(2017))); - assertThat(countYear2017[1], is(1l)); - } - - @Test - public void whenQueryWithAggregation_thenReturnCustomResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYearClass(); - - CommentCount countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019.getYear(), is(Integer.valueOf(2019))); - assertThat(countYear2019.getTotal(), is(1l)); - - CommentCount countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018.getYear(), is(Integer.valueOf(2018))); - assertThat(countYear2018.getTotal(), is(2l)); - - CommentCount countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017.getYear(), is(Integer.valueOf(2017))); - assertThat(countYear2017.getTotal(), is(1l)); - } - - @Test - public void whenQueryWithAggregation_thenReturnInterfaceResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYearInterface(); - - ICommentCount countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); - assertThat(countYear2019.getTotalComment(), is(1l)); - - ICommentCount countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); - assertThat(countYear2018.getTotalComment(), is(2l)); - - ICommentCount countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); - assertThat(countYear2017.getTotalComment(), is(1l)); - } - - @Test - public void whenNativeQueryWithAggregation_thenReturnInterfaceResult() { - List commentCountsByYear = commentRepository.countTotalCommentsByYearNative(); - - ICommentCount countYear2019 = commentCountsByYear.get(0); - - assertThat(countYear2019.getYearComment(), is(Integer.valueOf(2019))); - assertThat(countYear2019.getTotalComment(), is(1l)); - - ICommentCount countYear2018 = commentCountsByYear.get(1); - - assertThat(countYear2018.getYearComment(), is(Integer.valueOf(2018))); - assertThat(countYear2018.getTotalComment(), is(2l)); - - ICommentCount countYear2017 = commentCountsByYear.get(2); - - assertThat(countYear2017.getYearComment(), is(Integer.valueOf(2017))); - assertThat(countYear2017.getTotalComment(), is(1l)); - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java deleted file mode 100644 index 5f4a36bc0e..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteFromRepositoryUnitTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.datajpadelete; - -import com.baeldung.Application; -import com.baeldung.datajpadelete.entity.Book; -import com.baeldung.datajpadelete.repository.BookRepository; -import org.junit.After; -import org.junit.Before; -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 org.springframework.transaction.annotation.Transactional; - -import java.util.Arrays; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class DeleteFromRepositoryUnitTest { - - @Autowired - private BookRepository repository; - - Book book1; - Book book2; - - @Before - public void setup() { - book1 = new Book("The Hobbit"); - book2 = new Book("All Quiet on the Western Front"); - - repository.saveAll(Arrays.asList(book1, book2)); - } - - @After - public void teardown() { - repository.deleteAll(); - } - - @Test - public void whenDeleteByIdFromRepository_thenDeletingShouldBeSuccessful() { - repository.deleteById(book1.getId()); - - assertThat(repository.count()).isEqualTo(1); - } - - @Test - public void whenDeleteAllFromRepository_thenRepositoryShouldBeEmpty() { - repository.deleteAll(); - - assertThat(repository.count()).isEqualTo(0); - } - - @Test - @Transactional - public void whenDeleteFromDerivedQuery_thenDeletingShouldBeSuccessful() { - long deletedRecords = repository.deleteByTitle("The Hobbit"); - - assertThat(deletedRecords).isEqualTo(1); - } - - @Test - @Transactional - public void whenDeleteFromCustomQuery_thenDeletingShouldBeSuccessful() { - repository.deleteBooks("The Hobbit"); - - assertThat(repository.count()).isEqualTo(1); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java deleted file mode 100644 index 6275ace6e0..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/datajpadelete/DeleteInRelationshipsUnitTest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.datajpadelete; - -import com.baeldung.Application; -import com.baeldung.datajpadelete.entity.Book; -import com.baeldung.datajpadelete.entity.Category; -import com.baeldung.datajpadelete.repository.BookRepository; -import com.baeldung.datajpadelete.repository.CategoryRepository; -import org.junit.After; -import org.junit.Before; -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.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class DeleteInRelationshipsUnitTest { - - @Autowired - private BookRepository bookRepository; - - @Autowired - private CategoryRepository categoryRepository; - - @Before - public void setup() { - Book book1 = new Book("The Hobbit"); - Category category1 = new Category("Cat1", book1); - categoryRepository.save(category1); - - Book book2 = new Book("All Quiet on the Western Front"); - Category category2 = new Category("Cat2", book2); - categoryRepository.save(category2); - } - - @After - public void teardown() { - bookRepository.deleteAll(); - categoryRepository.deleteAll(); - } - - @Test - public void whenDeletingCategories_thenBooksShouldAlsoBeDeleted() { - categoryRepository.deleteAll(); - - assertThat(bookRepository.count()).isEqualTo(0); - assertThat(categoryRepository.count()).isEqualTo(0); - } - - @Test - public void whenDeletingBooks_thenCategoriesShouldAlsoBeDeleted() { - bookRepository.deleteAll(); - - assertThat(bookRepository.count()).isEqualTo(0); - assertThat(categoryRepository.count()).isEqualTo(2); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java deleted file mode 100644 index b4c365a2d9..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/embeddable/EmbeddableIntegrationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.baeldung.embeddable; - -import com.baeldung.Application; -import com.baeldung.embeddable.model.Company; -import com.baeldung.embeddable.model.ContactPerson; -import com.baeldung.embeddable.repositories.CompanyRepository; -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 org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class EmbeddableIntegrationTest { - - @Autowired - private CompanyRepository companyRepository; - - @Test - @Transactional - public void whenInsertingCompany_thenEmbeddedContactPersonDetailsAreMapped() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("First"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - Company result = companyRepository.getOne(company.getId()); - - assertEquals("Company", result.getName()); - assertEquals("1st street", result.getAddress()); - assertEquals("987-654-321", result.getPhone()); - assertEquals("First", result.getContactPerson().getFirstName()); - assertEquals("Last", result.getContactPerson().getLastName()); - assertEquals("123-456-789", result.getContactPerson().getPhone()); - } - - @Test - @Transactional - public void whenFindingCompanyByContactPersonAttribute_thenCompanyIsReturnedProperly() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("Name"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - List result = companyRepository.findByContactPersonFirstName("Name"); - - assertEquals(1, result.size()); - - result = companyRepository.findByContactPersonFirstName("FirstName"); - - assertEquals(0, result.size()); - } - - @Test - @Transactional - public void whenFindingCompanyByContactPersonAttributeWithJPQL_thenCompanyIsReturnedProperly() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("@QueryName"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - List result = companyRepository.findByContactPersonFirstNameWithJPQL("@QueryName"); - - assertEquals(1, result.size()); - - result = companyRepository.findByContactPersonFirstNameWithJPQL("FirstName"); - - assertEquals(0, result.size()); - } - - @Test - @Transactional - public void whenFindingCompanyByContactPersonAttributeWithNativeQuery_thenCompanyIsReturnedProperly() { - ContactPerson contactPerson = new ContactPerson(); - contactPerson.setFirstName("NativeQueryName"); - contactPerson.setLastName("Last"); - contactPerson.setPhone("123-456-789"); - - Company company = new Company(); - company.setName("Company"); - company.setAddress("1st street"); - company.setPhone("987-654-321"); - company.setContactPerson(contactPerson); - - companyRepository.save(company); - - List result = companyRepository.findByContactPersonFirstNameWithNativeQuery("NativeQueryName"); - - assertEquals(1, result.size()); - - result = companyRepository.findByContactPersonFirstNameWithNativeQuery("FirstName"); - - assertEquals(0, result.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java deleted file mode 100644 index 24880a5dff..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/entitygraph/EntityGraphIntegrationTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.entitygraph; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.entitygraph.model.Characteristic; -import com.baeldung.entitygraph.model.Item; -import com.baeldung.entitygraph.repository.CharacteristicsRepository; -import com.baeldung.entitygraph.repository.ItemRepository; - -@DataJpaTest -@RunWith(SpringRunner.class) -@Sql(scripts = "/entitygraph-data.sql") -public class EntityGraphIntegrationTest { - - @Autowired - private ItemRepository itemRepo; - - @Autowired - private CharacteristicsRepository characteristicsRepo; - - @Test - public void givenEntityGraph_whenCalled_shouldRetrunDefinedFields() { - Item item = itemRepo.findByName("Table"); - assertThat(item.getId()).isEqualTo(1L); - } - - @Test - public void givenAdhocEntityGraph_whenCalled_shouldRetrunDefinedFields() { - Characteristic characteristic = characteristicsRepo.findByType("Rigid"); - assertThat(characteristic.getId()).isEqualTo(1L); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java deleted file mode 100644 index d99f6671a3..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/exists/CarRepositoryIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.exists; - -import com.baeldung.Application; -import org.junit.After; -import org.junit.Before; -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.data.domain.Example; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.ignoreCase; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = {Application.class}) -public class CarRepositoryIntegrationTest { - - @Autowired - private CarRepository repository; - private int searchId; - - @Before - public void setup() { - List cars = repository.saveAll(Arrays.asList(new Car(200, "BMW"), new Car(300, "Audi"))); - searchId = cars.get(0).getId(); - } - - @After - public void teardown() { - repository.deleteAll(); - } - - @Test - public void whenIdIsCorrect_thenExistsShouldReturnTrue() { - assertThat(repository.existsById(searchId)).isTrue(); - } - - @Test - public void givenExample_whenExists_thenIsTrue() { - ExampleMatcher modelMatcher = ExampleMatcher.matching() - .withIgnorePaths("id") // must explicitly ignore -> PK - .withMatcher("model", ignoreCase()); - Car probe = new Car(); - probe.setModel("bmw"); - - Example example = Example.of(probe, modelMatcher); - - assertThat(repository.exists(example)).isTrue(); - } - - @Test - public void givenPower_whenExists_thenIsFalse() { - assertThat(repository.existsCarByPower(200)).isTrue(); - assertThat(repository.existsCarByPower(800)).isFalse(); - } - - @Test - public void existsByDerivedQuery_byModel() { - assertThat(repository.existsCarByModel("Audi")).isTrue(); - assertThat(repository.existsCarByModel("audi")).isFalse(); - assertThat(repository.existsCarByModel("AUDI")).isFalse(); - assertThat(repository.existsCarByModel("")).isFalse(); - } - - @Test - public void givenModelName_whenExistsExact_thenIsTrue() { - assertThat(repository.existsCarExactCustomQuery("BMW")).isTrue(); - assertThat(repository.existsCarExactCustomQuery("Bmw")).isFalse(); - assertThat(repository.existsCarExactCustomQuery("bmw")).isFalse(); - assertThat(repository.existsCarExactCustomQuery("")).isFalse(); - } - - @Test - public void givenModelName_whenExistsLike_thenIsTrue() { - assertThat(repository.existsCarLikeCustomQuery("BMW")).isTrue(); - assertThat(repository.existsCarLikeCustomQuery("Bmw")).isTrue(); - assertThat(repository.existsCarLikeCustomQuery("bmw")).isTrue(); - assertThat(repository.existsCarLikeCustomQuery("")).isFalse(); - } - -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java deleted file mode 100644 index 9b0d23f3e4..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/joins/JpaJoinsIntegrationTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.baeldung.joins; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.baeldung.joins.model.Department; -import com.baeldung.joins.model.Phone; -import java.util.Collection; -import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@DataJpaTest -@ActiveProfiles("joins") -public class JpaJoinsIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void whenPathExpressionIsUsedForSingleValuedAssociation_thenCreatesImplicitInnerJoin() { - TypedQuery query = entityManager.createQuery("SELECT e.department FROM Employee e", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e JOIN e.department d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenInnerJoinKeywordIsUsed_thenCreatesExplicitInnerJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e INNER JOIN e.department d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenEntitiesAreListedInFromAndMatchedInWhere_ThenCreatesJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e, Department d WHERE e.department = d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenEntitiesAreListedInFrom_ThenCreatesCartesianProduct() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Employee e, Department d", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(9); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Management", "Infra", "Accounting", "Management", "Infra", "Accounting", "Management"); - } - - @Test - public void whenCollectionValuedAssociationIsJoined_ThenCanSelect() { - TypedQuery query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.phones ph WHERE ph LIKE '1%'", Phone.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(1); - } - - @Test - public void whenMultipleEntitiesAreListedWithJoin_ThenCreatesMultipleJoins() { - TypedQuery query = entityManager.createQuery("SELECT ph FROM Employee e JOIN e.department d JOIN e.phones ph WHERE d.name IS NOT NULL", Phone.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("number") - .containsOnly("111", "222", "333"); - } - - @Test - public void whenLeftKeywordIsSpecified_thenCreatesOuterJoinAndIncludesNonMatched() { - TypedQuery query = entityManager.createQuery("SELECT DISTINCT d FROM Department d LEFT JOIN d.employees e", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Management"); - } - - @Test - public void whenFetchKeywordIsSpecified_ThenCreatesFetchJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Department d JOIN FETCH d.employees", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(3); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting"); - } - - @Test - public void whenLeftAndFetchKeywordsAreSpecified_ThenCreatesOuterFetchJoin() { - TypedQuery query = entityManager.createQuery("SELECT d FROM Department d LEFT JOIN FETCH d.employees", Department.class); - - List resultList = query.getResultList(); - - assertThat(resultList).hasSize(4); - assertThat(resultList).extracting("name") - .containsOnly("Infra", "Accounting", "Accounting", "Management"); - } - - @Test - public void whenCollectionValuedAssociationIsSpecifiedInSelect_ThenReturnsCollections() { - TypedQuery query = entityManager.createQuery("SELECT e.phones FROM Employee e", Collection.class); - - List resultList = query.getResultList(); - - assertThat(resultList).extracting("number").containsOnly("111", "222", "333"); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java deleted file mode 100644 index 96eaf4ed07..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.projection; - -import com.baeldung.projection.model.Person; -import com.baeldung.projection.repository.AddressRepository; -import com.baeldung.projection.repository.PersonRepository; -import com.baeldung.projection.view.AddressView; -import com.baeldung.projection.view.PersonDto; -import com.baeldung.projection.view.PersonView; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; - -@DataJpaTest -@RunWith(SpringRunner.class) -@Sql(scripts = "/projection-insert-data.sql") -@Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD) -public class JpaProjectionIntegrationTest { - @Autowired - private AddressRepository addressRepository; - - @Autowired - private PersonRepository personRepository; - - @Test - public void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() { - AddressView addressView = addressRepository.getAddressByState("CA").get(0); - assertThat(addressView.getZipCode()).isEqualTo("90001"); - - PersonView personView = addressView.getPerson(); - assertThat(personView.getFirstName()).isEqualTo("John"); - assertThat(personView.getLastName()).isEqualTo("Doe"); - } - - @Test - public void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() { - PersonView personView = personRepository.findByLastName("Doe"); - assertThat(personView.getFullName()).isEqualTo("John Doe"); - } - - @Test - public void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() { - PersonDto personDto = personRepository.findByFirstName("John"); - assertThat(personDto.getFirstName()).isEqualTo("John"); - assertThat(personDto.getLastName()).isEqualTo("Doe"); - } - - @Test - public void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() { - Person person = personRepository.findByLastName("Doe", Person.class); - PersonView personView = personRepository.findByLastName("Doe", PersonView.class); - PersonDto personDto = personRepository.findByLastName("Doe", PersonDto.class); - - assertThat(person.getFirstName()).isEqualTo("John"); - assertThat(personView.getFirstName()).isEqualTo("John"); - assertThat(personDto.getFirstName()).isEqualTo("John"); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java deleted file mode 100644 index 5d6457ce30..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Customer; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@DataJpaTest -@RunWith(SpringRunner.class) -public class CustomerRepositoryIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private CustomerRepository repository; - - @Before - public void before() { - entityManager.persist(new Customer("A", "A@example.com")); - entityManager.persist(new Customer("D", null)); - entityManager.persist(new Customer("D", "D@example.com")); - } - - @Test - public void givenQueryMethod_whenEmailIsNull_thenFoundByNullEmail() { - List customers = repository.findByNameAndEmail("D", null); - - assertEquals(1, customers.size()); - Customer actual = customers.get(0); - - assertEquals(null, actual.getEmail()); - assertEquals("D", actual.getName()); - } - - @Test - public void givenQueryMethod_whenEmailIsAbsent_thenIgnoreEmail() { - List customers = repository.findByName("D"); - - assertEquals(2, customers.size()); - } - - @Test - public void givenQueryAnnotation_whenEmailIsNull_thenIgnoreEmail() { - List customers = repository.findCustomerByNameAndEmail("D", null); - - assertEquals(2, customers.size()); - } - - @After - public void cleanUp() { - repository.deleteAll(); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java deleted file mode 100644 index 4d3661e717..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -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 com.baeldung.entity.Fruit; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class FruitPopulatorIntegrationTest { - - @Autowired - private FruitRepository fruitRepository; - - @Test - public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() { - - List fruits = fruitRepository.findAll(); - assertEquals("record count is not matching", 2, fruits.size()); - - fruits.forEach(fruit -> { - if (1 == fruit.getId()) { - assertEquals("apple", fruit.getName()); - assertEquals("red", fruit.getColor()); - } else if (2 == fruit.getId()) { - assertEquals("guava", fruit.getName()); - assertEquals("green", fruit.getColor()); - } - }); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java deleted file mode 100644 index cf771dc833..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/FruitRepositoryIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.jupiter.api.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.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.entity.Fruit; - -@RunWith(SpringRunner.class) -@SpringBootTest -class FruitRepositoryIntegrationTest { - - @Autowired - private FruitRepository fruitRepository; - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByColor_ThenDeletedFruitsShouldReturn() { - - List fruits = fruitRepository.deleteByColor("green"); - - assertEquals("number of fruits are not matching", 2, fruits.size()); - fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByName_ThenDeletedFruitCountShouldReturn() { - - Long deletedFruitCount = fruitRepository.deleteByName("apple"); - - assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenRemovedByColor_ThenDeletedFruitsShouldReturn() { - - List fruits = fruitRepository.removeByColor("green"); - - assertEquals("number of fruits are not matching", 2, fruits.size()); - fruits.forEach(fruit -> assertEquals("Its not a green fruit", "green", fruit.getColor())); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenRemovedByName_ThenDeletedFruitCountShouldReturn() { - - Long deletedFruitCount = fruitRepository.removeByName("apple"); - - assertEquals("deleted fruit count is not matching", 1, deletedFruitCount.intValue()); - } - - @Transactional - @Test - @Sql(scripts = { "/test-fruit-data.sql" }) - public void givenFruits_WhenDeletedByColorOrName_ThenDeletedFruitsShouldReturn() { - - int deletedCount = fruitRepository.deleteFruits("apple", "green"); - - assertEquals("number of fruits are not matching", 3, deletedCount); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java deleted file mode 100644 index f96f0249d7..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.baeldung.repository; - -import com.baeldung.entity.Passenger; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.core.IsNot.not; - -@DataJpaTest -@RunWith(SpringRunner.class) -public class PassengerRepositoryIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - @Autowired - private PassengerRepository repository; - - @Before - public void before() { - entityManager.persist(Passenger.from("Jill", "Smith")); - entityManager.persist(Passenger.from("Eve", "Jackson")); - entityManager.persist(Passenger.from("Fred", "Bloggs")); - entityManager.persist(Passenger.from("Ricki", "Bobbie")); - entityManager.persist(Passenger.from("Siya", "Kolisi")); - } - - @Test - public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith"); - Passenger eve = Passenger.from("Eve", "Jackson"); - Passenger fred = Passenger.from("Fred", "Bloggs"); - Passenger siya = Passenger.from("Siya", "Kolisi"); - Passenger ricki = Passenger.from("Ricki", "Bobbie"); - - List passengers = repository.findByFirstNameIgnoreCase("FRED"); - - assertThat(passengers, contains(fred)); - assertThat(passengers, not(contains(eve))); - assertThat(passengers, not(contains(siya))); - assertThat(passengers, not(contains(jill))); - assertThat(passengers, not(contains(ricki))); - - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java deleted file mode 100644 index 14912a4ecb..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -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.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.entity.Song; - -@RunWith(SpringRunner.class) -@SpringBootTest -@Sql(scripts = { "/test-song-data.sql" }) -public class SongRepositoryIntegrationTest { - - @Autowired private SongRepository songRepository; - - @Transactional - @Test - public void givenSong_WhenFindLikeByName_ThenShouldReturnOne() { - List songs = songRepository.findByNameLike("Despacito"); - assertEquals(1, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindByNameNotLike_thenShouldReturn3Songs() { - List songs = songRepository.findByNameNotLike("Despacito"); - assertEquals(5, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindByNameStartingWith_thenShouldReturn2Songs() { - List songs = songRepository.findByNameStartingWith("Co"); - assertEquals(2, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindByNameEndingWith_thenShouldReturn2Songs() { - List songs = songRepository.findByNameEndingWith("Life"); - assertEquals(2, songs.size()); - } - - @Transactional - @Test - public void givenSong_WhenFindBySingerContaining_thenShouldReturn2Songs() { - List songs = songRepository.findBySingerContaining("Luis"); - assertEquals(2, songs.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql deleted file mode 100644 index 685ec2c605..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/entitygraph-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO Item(id,name) VALUES (1,'Table'); -INSERT INTO Item(id,name) VALUES (2,'Bottle'); - -INSERT INTO Characteristic(id,item_id, type) VALUES (1,1,'Rigid'); -INSERT INTO Characteristic(id,item_id,type) VALUES (2,1,'Big'); -INSERT INTO Characteristic(id,item_id,type) VALUES (3,2,'Fragile'); -INSERT INTO Characteristic(id,item_id,type) VALUES (4,2,'Small'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql deleted file mode 100644 index d34f6f0636..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-clean-up-data.sql +++ /dev/null @@ -1,2 +0,0 @@ -DELETE FROM address; -DELETE FROM person; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql deleted file mode 100644 index 544dcc4b88..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/projection-insert-data.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT INTO person(id,first_name,last_name) VALUES (1,'John','Doe'); -INSERT INTO address(id,person_id,state,city,street,zip_code) VALUES (1,1,'CA', 'Los Angeles', 'Standford Ave', '90001'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql deleted file mode 100644 index 12409a124e..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/test-aggregation-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO post (id, title, content) VALUES (1, 'Comment 1', 'Content 1'); -INSERT INTO post (id, title, content) VALUES (2, 'Comment 2', 'Content 2'); -INSERT INTO post (id, title, content) VALUES (3, 'Comment 3', 'Content 3'); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (1, 2019, false, 'Comment 1', 1); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (2, 2018, true, 'Comment 2', 1); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (3, 2018, true, 'Comment 3', 2); -INSERT INTO comment (id, year, approved, content, post_id) VALUES (4, 2017, false, 'Comment 4', 3); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql deleted file mode 100644 index d99f42e5a7..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/test-fruit-data.sql +++ /dev/null @@ -1,6 +0,0 @@ -truncate table fruit; - -insert into fruit(id,name,color) values (1,'apple','red'); -insert into fruit(id,name,color) values (2,'custard apple','green'); -insert into fruit(id,name,color) values (3,'mango','yellow'); -insert into fruit(id,name,color) values (4,'guava','green'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql b/persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql deleted file mode 100644 index 5a2b1a5555..0000000000 --- a/persistence-modules/spring-data-jpa-2/src/test/resources/test-song-data.sql +++ /dev/null @@ -1,8 +0,0 @@ -INSERT INTO song(id,name,length_in_seconds,compositor,singer,released,genre) -VALUES -(1,'Despacito',209,'Luis Fonsi','Luis Fonsi, Daddy Yankee','2017-01-12','Reggaeton'), -(2,'Con calma',188,'Daddy Yankee','Daddy Yankee','2019-01-24','Reggaeton'), -(3,'It''s My Life',205,'Bon Jovi','Jon Bon Jovi','2000-05-23','Pop'), -(4,'Live is Life',242,'Opus','Opus','1985-01-01','Reggae'), -(5,'Countdown to Extinction',249,'Megadeth','Megadeth','1992-07-14','Heavy Metal'), -(6, 'Si nos dejan',139,'Luis Miguel','Luis Miguel','1995-10-17','Bolero'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/README.md b/persistence-modules/spring-data-jpa-3/README.md deleted file mode 100644 index bac52bf114..0000000000 --- a/persistence-modules/spring-data-jpa-3/README.md +++ /dev/null @@ -1,20 +0,0 @@ -### Relevant Articles: -- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) -- [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) -- [INSERT Statement in JPA](https://www.baeldung.com/jpa-insert) -- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) -- [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) -- [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) -- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) -- [Spring Data JPA Batch Inserts](https://www.baeldung.com/spring-data-jpa-batch-inserts) -- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update) -- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-3/pom.xml b/persistence-modules/spring-data-jpa-3/pom.xml deleted file mode 100644 index d02d089ba3..0000000000 --- a/persistence-modules/spring-data-jpa-3/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - spring-data-jpa-3 - spring-data-jpa-3 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - com.google.guava - guava - ${guava.version} - - - com.h2database - h2 - - - net.ttddyy - datasource-proxy - ${datasource-proxy.version} - - - org.postgresql - postgresql - - - com.h2database - h2 - runtime - - - - - org.testcontainers - postgresql - ${testcontainers.version} - test - - - - - - 1.4.1 - 21.0 - 1.12.2 - - - diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java deleted file mode 100644 index ce10072031..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -@EnableJpaRepositories -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java deleted file mode 100644 index 504357db44..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/DatasourceProxyBeanPostProcessor.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.batchinserts; - -import java.lang.reflect.Method; -import javax.sql.DataSource; -import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Component; -import org.springframework.util.ReflectionUtils; - -@Component -@Profile("batchinserts") -public class DatasourceProxyBeanPostProcessor implements BeanPostProcessor { - - @Override - public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException { - return bean; - } - - @Override - public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { - if (bean instanceof DataSource) { - ProxyFactory factory = new ProxyFactory(bean); - factory.setProxyTargetClass(true); - factory.addAdvice(new ProxyDataSourceInterceptor((DataSource) bean)); - return factory.getProxy(); - } - - return bean; - } - - private static class ProxyDataSourceInterceptor implements MethodInterceptor { - - private final DataSource dataSource; - - public ProxyDataSourceInterceptor(final DataSource dataSource) { - this.dataSource = ProxyDataSourceBuilder.create(dataSource).name("Batch-Insert-Logger").asJson().countQuery().logQueryToSysOut().build(); - } - - @Override - public Object invoke(final MethodInvocation invocation) throws Throwable { - Method proxyMethod = ReflectionUtils.findMethod(dataSource.getClass(), invocation.getMethod().getName()); - if (proxyMethod != null) { - return proxyMethod.invoke(dataSource, invocation.getArguments()); - } - return invocation.proceed(); - } - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java deleted file mode 100644 index 6d2f333ac7..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/School.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.batchinserts.model; - -import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class School { - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private long id; - - private String name; - - @OneToMany(mappedBy = "school") - private List students; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getStudents() { - return students; - } - - public void setStudents(List students) { - this.students = students; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java deleted file mode 100644 index d38214f122..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/batchinserts/model/Student.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.baeldung.batchinserts.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class Student { - - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private long id; - - private String name; - - @ManyToOne - private School school; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public School getSchool() { - return school; - } - - public void setSchool(School school) { - this.school = school; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java deleted file mode 100644 index aaca760499..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -@SpringBootApplication -@EnableJpaRepositories("com.baeldung") -@EntityScan("com.baeldung") -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java deleted file mode 100644 index 7cb7e45b27..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/CustomerRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.boot.domain.Customer; - -/** - * JPA CrudRepository interface - * - * @author ysharma2512 - * - */ -@Repository -@Transactional -public interface CustomerRepository extends CrudRepository{ - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java deleted file mode 100644 index 373532e1c3..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/impl/PersonInsertRepository.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Person; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.transaction.Transactional; - -@Repository -public class PersonInsertRepository { - - @PersistenceContext - private EntityManager entityManager; - - @Transactional - public void insertWithQuery(Person person) { - entityManager.createNativeQuery("INSERT INTO person (id, first_name, last_name) VALUES (?,?,?)") - .setParameter(1, person.getId()) - .setParameter(2, person.getFirstName()) - .setParameter(3, person.getLastName()) - .executeUpdate(); - } - - @Transactional - public void insertWithEntityManager(Person person) { - this.entityManager.persist(person); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java deleted file mode 100644 index 53f692ff28..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.boot.daos.user; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.User; - -import java.time.LocalDate; -import java.util.Collection; -import java.util.List; -import java.util.stream.Stream; - -public interface UserRepository extends JpaRepository , UserRepositoryCustom{ - - Stream findAllByName(String name); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query("select u from User u where u.email like '%@gmail.com'") - List findUsersWithGmailAddress(); - - @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true) - Collection findAllActiveUsersNative(); - - @Query("SELECT u FROM User u WHERE u.status = ?1") - User findUserByStatus(Integer status); - - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) - User findUserByStatusNative(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") - User findUserByStatusAndName(Integer status, String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) - User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - - @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) - @Modifying - void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); - - @Modifying - @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNativePostgres(Integer status, String name); - - @Query(value = "SELECT u FROM User u WHERE u.name IN :names") - List findUserByNameList(@Param("names") Collection names); - - void deleteAllByCreationDateAfter(LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("update User u set u.active = false where u.lastLoginDate < :date") - void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("delete User u where u.active = false") - int deleteDeactivatedUsers(); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) - void addDeletedColumn(); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java deleted file mode 100644 index c586b54027..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import com.baeldung.boot.domain.User; - -public interface UserRepositoryCustom { - List findUserByEmails(Set emails); - - List findAllUsersByPredicates(Collection> predicates); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java deleted file mode 100644 index 63a743b6b5..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import com.baeldung.boot.domain.User; - -public class UserRepositoryCustomImpl implements UserRepositoryCustom { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findUserByEmails(Set emails) { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(User.class); - Root user = query.from(User.class); - - Path emailPath = user.get("email"); - - List predicates = new ArrayList<>(); - for (String email : emails) { - - predicates.add(cb.like(emailPath, email)); - - } - query.select(user) - .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); - - return entityManager.createQuery(query) - .getResultList(); - } - - @Override - public List findAllUsersByPredicates(Collection> predicates) { - List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); - Stream allUsersStream = allUsers.stream(); - for (java.util.function.Predicate predicate : predicates) { - allUsersStream = allUsersStream.filter(predicate); - } - - return allUsersStream.collect(Collectors.toList()); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java deleted file mode 100644 index af88be0be6..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Customer.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -/** - * Customer Entity class - * @author ysharma2512 - * - */ -@Entity -public class Customer { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - private String firstName; - private String lastName; - - public Customer(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - @Override - public String toString() { - return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java deleted file mode 100644 index 88894ccc72..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Person.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Person { - - @Id - private Long id; - private String firstName; - private String lastName; - - public Person() { - } - - public Person(Long id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java deleted file mode 100644 index f13491ad82..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/Possession.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; -import com.baeldung.boot.domain.Possession; - -@Entity -@Table -public class Possession { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public Possession() { - super(); - } - - public Possession(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Possession other = (Possession) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java deleted file mode 100644 index cca00e52a2..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/domain/User.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; - -import java.time.LocalDate; -import java.util.List; -import java.util.Objects; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String name; - private LocalDate creationDate; - private LocalDate lastLoginDate; - private boolean active; - private int age; - @Column(unique = true, nullable = false) - private String email; - private Integer status; - @OneToMany - List possessionList; - - public User() { - super(); - } - - public User(String name, LocalDate creationDate,String email, Integer status) { - this.name = name; - this.creationDate = creationDate; - this.email = email; - this.status = status; - this.active = true; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - public LocalDate getCreationDate() { - return creationDate; - } - - public List getPossessionList() { - return possessionList; - } - - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - User user = (User) o; - return id == user.id && - age == user.age && - Objects.equals(name, user.name) && - Objects.equals(creationDate, user.creationDate) && - Objects.equals(email, user.email) && - Objects.equals(status, user.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, name, creationDate, age, email, status); - } - - public LocalDate getLastLoginDate() { - return lastLoginDate; - } - - public void setLastLoginDate(LocalDate lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java deleted file mode 100644 index 7152286c83..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/CustomPassengerRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.boot.passenger; - -import java.util.List; - -interface CustomPassengerRepository { - - List findOrderedBySeatNumberLimitedTo(int limit); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java deleted file mode 100644 index c75107a783..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/Passenger.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.boot.passenger; - -import javax.persistence.Basic; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import java.util.Objects; - -@Entity -class Passenger { - - @Id - @GeneratedValue - @Column(nullable = false) - private Long id; - - @Basic(optional = false) - @Column(nullable = false) - private String firstName; - - @Basic(optional = false) - @Column(nullable = false) - private String lastName; - - @Basic(optional = false) - @Column(nullable = false) - private Integer seatNumber; - - private Passenger(String firstName, String lastName, Integer seatNumber) { - this.firstName = firstName; - this.lastName = lastName; - this.seatNumber = seatNumber; - } - - static Passenger from(String firstName, String lastName, Integer seatNumber) { - return new Passenger(firstName, lastName, seatNumber); - } - - @Override - public boolean equals(Object object) { - if (this == object) - return true; - if (object == null || getClass() != object.getClass()) - return false; - Passenger passenger = (Passenger) object; - return getSeatNumber() == passenger.getSeatNumber() && Objects.equals(getFirstName(), passenger.getFirstName()) - && Objects.equals(getLastName(), passenger.getLastName()); - } - - @Override - public int hashCode() { - return Objects.hash(getFirstName(), getLastName(), getSeatNumber()); - } - - @Override - public String toString() { - final StringBuilder toStringBuilder = new StringBuilder(getClass().getSimpleName()); - toStringBuilder.append("{ id=").append(id); - toStringBuilder.append(", firstName='").append(firstName).append('\''); - toStringBuilder.append(", lastName='").append(lastName).append('\''); - toStringBuilder.append(", seatNumber=").append(seatNumber); - toStringBuilder.append('}'); - return toStringBuilder.toString(); - } - - Long getId() { - return id; - } - - String getFirstName() { - return firstName; - } - - String getLastName() { - return lastName; - } - - Integer getSeatNumber() { - return seatNumber; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java deleted file mode 100644 index 14d5403cb5..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.boot.passenger; - -import java.util.List; - -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; - -interface PassengerRepository extends JpaRepository, CustomPassengerRepository { - - Passenger findFirstByOrderBySeatNumberAsc(); - - Passenger findTopByOrderBySeatNumberAsc(); - - List findByOrderBySeatNumberAsc(); - - List findByFirstNameIgnoreCase(String firstName); - - List findByLastNameOrderBySeatNumberAsc(String lastName); - - List findByLastName(String lastName, Sort sort); - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java deleted file mode 100644 index 508c669066..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/passenger/PassengerRepositoryImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.boot.passenger; - -import org.springframework.stereotype.Repository; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; - -@Repository -class PassengerRepositoryImpl implements CustomPassengerRepository { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findOrderedBySeatNumberLimitedTo(int limit) { - return entityManager.createQuery("SELECT p FROM Passenger p ORDER BY p.seatNumber", - Passenger.class).setMaxResults(limit).getResultList(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java deleted file mode 100644 index e13afd9b45..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/boot/web/controllers/CustomerController.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.boot.web.controllers; - -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.List; - -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.boot.daos.CustomerRepository; -import com.baeldung.boot.domain.Customer; - -/** - * A simple controller to test the JPA CrudRepository operations - * controllers - * - * @author ysharma2512 - * - */ -@RestController -public class CustomerController { - - CustomerRepository customerRepository; - - public CustomerController(CustomerRepository customerRepository2) { - this.customerRepository = customerRepository2; - } - - @PostMapping("/customers") - public ResponseEntity> insertCustomers() throws URISyntaxException { - Customer c1 = new Customer("James", "Gosling"); - Customer c2 = new Customer("Doug", "Lea"); - Customer c3 = new Customer("Martin", "Fowler"); - Customer c4 = new Customer("Brian", "Goetz"); - List customers = Arrays.asList(c1, c2, c3, c4); - customerRepository.saveAll(customers); - return ResponseEntity.ok(customers); - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java deleted file mode 100644 index 4c3dbd25b7..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/entity/Employee.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Employee { - - @Id - private Long id; - private String name; - - public Employee() { - } - - public Employee(Long id, String name) { - this.id = id; - this.name = name; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java deleted file mode 100644 index 2dc9c18cf6..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/model/BasicUser.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.model; - -import javax.persistence.*; -import java.util.Set; - -@Entity -@Table(name = "users") -public class BasicUser { - - @Id - @GeneratedValue - private Long id; - - private String username; - - @ElementCollection - private Set permissions; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java deleted file mode 100644 index 3b9aa2cc18..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.multipledb; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MultipleDbApplication { - - public static void main(String[] args) { - SpringApplication.run(MultipleDbApplication.class, args); - } - -} - diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java deleted file mode 100644 index bcf2cd84eb..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.multipledb; - -import com.google.common.base.Preconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.util.HashMap; - -@Configuration -@PropertySource({"classpath:persistence-multiple-db.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -@Profile("!tc") -public class PersistenceProductConfiguration { - @Autowired - private Environment env; - - public PersistenceProductConfiguration() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.product"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - public DataSource productDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java deleted file mode 100644 index 6ce9bcad45..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.multipledb.dao.product; - -import java.util.List; - -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.PagingAndSortingRepository; - -import com.baeldung.multipledb.model.product.Product; - -public interface ProductRepository extends PagingAndSortingRepository { - - List findAllByPrice(double price, Pageable pageable); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java deleted file mode 100644 index eaf471043c..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/multipledb/model/product/Product.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.multipledb.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "products") -public class Product { - - @Id - private int id; - - private String name; - - private double price; - - public Product() { - super(); - } - - private Product(int id, String name, double price) { - super(); - this.id = id; - this.name = name; - this.price = price; - } - - public static Product from(int id, String name, double price) { - return new Product(id, name, price); - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(final double price) { - this.price = price; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=") - .append(name) - .append(", id=") - .append(id) - .append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java deleted file mode 100644 index 8f0a80814b..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/EmployeeRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.repository; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.entity.Employee; - -public interface EmployeeRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java b/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java deleted file mode 100644 index f683be402f..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/java/com/baeldung/repository/UserRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.repository; - -import java.util.Optional; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.model.BasicUser; - -public interface UserRepository extends JpaRepository { - - Optional findSummaryByUsername(String username); - - Optional findByUsername(String username); -} diff --git a/persistence-modules/spring-data-jpa-3/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-3/src/main/resources/application.properties deleted file mode 100644 index f127dd5e50..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.main.allow-bean-definition-overriding=true - -spring.jpa.properties.hibernate.jdbc.batch_size=4 -spring.jpa.properties.hibernate.order_inserts=true -spring.jpa.properties.hibernate.order_updates=true -spring.jpa.properties.hibernate.generate_statistics=true diff --git a/persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties deleted file mode 100644 index 75534e8a54..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/main/resources/persistence-multiple-db.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS -jdbc.user=sa -jdbc.pass=sa - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index eaccf4acba..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java deleted file mode 100644 index 27c71c5bcc..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@DataJpaTest -@ContextConfiguration(classes = Application.class) -public class SpringJpaContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java deleted file mode 100644 index 7ddf36d3f0..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/BatchInsertIntegrationTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.batchinserts; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; - -import com.baeldung.boot.Application; -import com.baeldung.boot.daos.CustomerRepository; -import com.baeldung.boot.web.controllers.CustomerController; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -@AutoConfigureMockMvc -public class BatchInsertIntegrationTest { - - @Autowired - private CustomerRepository customerRepository; - private MockMvc mockMvc; - @Before - public void setUp() throws Exception { - mockMvc = MockMvcBuilders.standaloneSetup( new CustomerController(customerRepository)) - .build(); - } - - @Test - public void whenInsertingCustomers_thenCustomersAreCreated() throws Exception { - this.mockMvc.perform(post("/customers")) - .andExpect(status().isOk()); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java deleted file mode 100644 index 311f227322..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaBatchInsertsIntegrationTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.baeldung.batchinserts; - -import static com.baeldung.batchinserts.TestObjectHelper.createSchool; -import static com.baeldung.batchinserts.TestObjectHelper.createStudent; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.TypedQuery; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.batchinserts.model.School; -import com.baeldung.batchinserts.model.Student; -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@Transactional -@ActiveProfiles("batchinserts") -public class JpaBatchInsertsIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - private static final int BATCH_SIZE = 5; - - @Transactional - @Test - public void whenInsertingSingleTypeOfEntity_thenCreatesSingleBatch() { - for (int i = 0; i < 10; i++) { - School school = createSchool(i); - entityManager.persist(school); - } - } - - @Transactional - @Test - public void whenFlushingAfterBatch_ThenClearsMemory() { - for (int i = 0; i < 10; i++) { - if (i > 0 && i % BATCH_SIZE == 0) { - entityManager.flush(); - entityManager.clear(); - } - - School school = createSchool(i); - entityManager.persist(school); - } - } - - @Transactional - @Test - public void whenThereAreMultipleEntities_ThenCreatesNewBatch() { - for (int i = 0; i < 10; i++) { - if (i > 0 && i % BATCH_SIZE == 0) { - entityManager.flush(); - entityManager.clear(); - } - - School school = createSchool(i); - entityManager.persist(school); - Student firstStudent = createStudent(school); - Student secondStudent = createStudent(school); - entityManager.persist(firstStudent); - entityManager.persist(secondStudent); - } - } - - @Transactional - @Test - public void whenUpdatingEntities_thenCreatesBatch() { - for (int i = 0; i < 10; i++) { - School school = createSchool(i); - entityManager.persist(school); - } - - entityManager.flush(); - - TypedQuery schoolQuery = entityManager.createQuery("SELECT s from School s", School.class); - List allSchools = schoolQuery.getResultList(); - - for (School school : allSchools) { - school.setName("Updated_" + school.getName()); - } - } - - @After - public void tearDown() { - entityManager.flush(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java deleted file mode 100644 index 75b3f1f3aa..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/JpaNoBatchInsertsIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.batchinserts; - -import static com.baeldung.batchinserts.TestObjectHelper.createSchool; - -import com.baeldung.batchinserts.model.School; -import com.baeldung.boot.Application; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@Transactional -@ActiveProfiles("batchinserts") -@TestPropertySource(properties = "spring.jpa.properties.hibernate.jdbc.batch_size=-1") -public class JpaNoBatchInsertsIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Test - public void whenNotConfigured_ThenSendsInsertsSeparately() { - for (int i = 0; i < 10; i++) { - School school = createSchool(i); - entityManager.persist(school); - } - } - - @After - public void tearDown() { - entityManager.flush(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java deleted file mode 100644 index fcd26cb721..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/batchinserts/TestObjectHelper.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.baeldung.batchinserts; - -import com.baeldung.batchinserts.model.School; -import com.baeldung.batchinserts.model.Student; - -public class TestObjectHelper { - - public static School createSchool(int nameIdentifier) { - School school = new School(); - school.setName("School" + (nameIdentifier + 1)); - return school; - } - - public static Student createStudent(School school) { - Student student = new Student(); - student.setName("Student-" + school.getName()); - student.setSchool(school); - return student; - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java deleted file mode 100644 index 9d45c17035..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/PersonInsertRepositoryIntegrationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.daos.impl.PersonInsertRepository; -import com.baeldung.boot.domain.Person; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.persistence.EntityExistsException; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceException; - -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -@RunWith(SpringRunner.class) -@DataJpaTest -@Import(PersonInsertRepository.class) -public class PersonInsertRepositoryIntegrationTest { - - private static final Long ID = 1L; - private static final String FIRST_NAME = "firstname"; - private static final String LAST_NAME = "lastname"; - private static final Person PERSON = new Person(ID, FIRST_NAME, LAST_NAME); - - @Autowired - private PersonInsertRepository personInsertRepository; - - @Autowired - private EntityManager entityManager; - - @Test - public void givenPersonEntity_whenInsertWithNativeQuery_ThenPersonIsPersisted() { - insertWithQuery(); - - assertPersonPersisted(); - } - - @Test - public void givenPersonEntity_whenInsertedTwiceWithNativeQuery_thenPersistenceExceptionExceptionIsThrown() { - assertThatExceptionOfType(PersistenceException.class).isThrownBy(() -> { - insertWithQuery(); - insertWithQuery(); - }); - } - - @Test - public void givenPersonEntity_whenInsertWithEntityManager_thenPersonIsPersisted() { - insertPersonWithEntityManager(); - - assertPersonPersisted(); - } - - @Test - public void givenPersonEntity_whenInsertedTwiceWithEntityManager_thenEntityExistsExceptionIsThrown() { - assertThatExceptionOfType(EntityExistsException.class).isThrownBy(() -> { - insertPersonWithEntityManager(); - insertPersonWithEntityManager(); - }); - } - - private void insertWithQuery() { - personInsertRepository.insertWithQuery(PERSON); - } - - private void insertPersonWithEntityManager() { - personInsertRepository.insertWithEntityManager(new Person(ID, FIRST_NAME, LAST_NAME)); - } - - private void assertPersonPersisted() { - Person person = entityManager.find(Person.class, ID); - - assertThat(person).isNotNull(); - assertThat(person.getId()).isEqualTo(PERSON.getId()); - assertThat(person.getFirstName()).isEqualTo(PERSON.getFirstName()); - assertThat(person.getLastName()).isEqualTo(PERSON.getLastName()); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java deleted file mode 100644 index b2581b8034..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ /dev/null @@ -1,545 +0,0 @@ -package com.baeldung.boot.daos; - -import org.junit.After; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.boot.daos.user.UserRepository; -import com.baeldung.boot.domain.User; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.time.LocalDate; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; - -public class UserRepositoryCommon { - - final String USER_EMAIL = "email@example.com"; - final String USER_EMAIL2 = "email2@example.com"; - final String USER_EMAIL3 = "email3@example.com"; - final String USER_EMAIL4 = "email4@example.com"; - final Integer INACTIVE_STATUS = 0; - final Integer ACTIVE_STATUS = 1; - final String USER_EMAIL5 = "email5@example.com"; - final String USER_EMAIL6 = "email6@example.com"; - final String USER_NAME_ADAM = "Adam"; - final String USER_NAME_PETER = "Peter"; - - @Autowired - protected UserRepository userRepository; - @Autowired - private EntityManager entityManager; - - @Test - @Transactional - public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - user4.setEmail(USER_EMAIL4); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAllUsers(Sort.by("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); - - assertThat(usersPage.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); - - assertThat(usersSortByNameLength.getContent() - .get(0) - .getName()).isEqualTo(USER_NAME_PETER); - } - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { - - User user1 = new User(); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - Set emails = new HashSet<>(); - emails.add(USER_EMAIL2); - emails.add(USER_EMAIL3); - - Collection usersWithEmails = userRepository.findUserByEmails(emails); - - assertThat(usersWithEmails.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindByNameListReturnCollection() { - - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); - - List usersWithNames = userRepository.findUserByNameList(names); - - assertThat(usersWithNames.size()).isEqualTo(2); - } - - - @Test - @Transactional - public void whenInsertedWithQuery_ThenUserIsPersisted() { - userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true); - userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true); - - User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM); - User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER); - - assertThat(userAdam).isNotNull(); - assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL); - assertThat(userPeter).isNotNull(); - assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2); - } - - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr01")) { - assertTrue(users.allMatch(usr -> usr.equals(usr01))); - } - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr00")) { - assertEquals(0, users.count()); - } - } - - @Test - public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List users = userRepository.findUsersWithGmailAddress(); - assertEquals(1, users.size()); - assertEquals(usr02, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); - - List users = userRepository.findAll(); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List> predicates = new ArrayList<>(); - predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); - predicates.add(usr -> usr.getEmail().endsWith(".com")); - - List users = userRepository.findAllUsersByPredicates(predicates); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); - - List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); - assertTrue(users.get(0).isActive()); - assertFalse(users.get(1).isActive()); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - int deletedUsersCount = userRepository.deleteDeactivatedUsers(); - - List users = userRepository.findAll(); - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - assertEquals(1, deletedUsersCount); - } - - @Test - @Transactional - public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.addDeletedColumn(); - - Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); - assertEquals(0, nativeQuery.getResultList().get(0)); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java deleted file mode 100644 index 99eabc8271..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import com.baeldung.util.BaeldungPostgresqlContainer; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles({"tc", "tc-auto"}) -public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java deleted file mode 100644 index be8843c166..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles("tc") -@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) -public class UserRepositoryTCLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") - .withDatabaseName("integration-tests-db") - .withUsername("sa") - .withPassword("sa"); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - static class Initializer - implements ApplicationContextInitializer { - public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of( - "spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(), - "spring.datasource.username=" + postgreSQLContainer.getUsername(), - "spring.datasource.password=" + postgreSQLContainer.getPassword() - ).applyTo(configurableApplicationContext.getEnvironment()); - } - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java deleted file mode 100644 index f082350019..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/boot/passenger/PassengerRepositoryIntegrationTest.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.baeldung.boot.passenger; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.data.domain.Example; -import org.springframework.data.domain.ExampleMatcher; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.passenger.Passenger; -import com.baeldung.boot.passenger.PassengerRepository; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.List; -import java.util.Optional; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - - -@DataJpaTest -@RunWith(SpringRunner.class) -public class PassengerRepositoryIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - @Autowired - private PassengerRepository repository; - - @Before - public void before() { - entityManager.persist(Passenger.from("Jill", "Smith", 50)); - entityManager.persist(Passenger.from("Eve", "Jackson", 95)); - entityManager.persist(Passenger.from("Fred", "Bloggs", 22)); - entityManager.persist(Passenger.from("Ricki", "Bobbie", 36)); - entityManager.persist(Passenger.from("Siya", "Kolisi", 85)); - } - - @Test - public void givenSeveralPassengersWhenOrderedBySeatNumberLimitedToThenThePassengerInTheFirstFilledSeatIsReturned() { - Passenger expected = Passenger.from("Fred", "Bloggs", 22); - - List passengers = repository.findOrderedBySeatNumberLimitedTo(1); - - assertEquals(1, passengers.size()); - - Passenger actual = passengers.get(0); - assertEquals(expected, actual); - } - - @Test - public void givenSeveralPassengersWhenFindFirstByOrderBySeatNumberAscThenThePassengerInTheFirstFilledSeatIsReturned() { - Passenger expected = Passenger.from("Fred", "Bloggs", 22); - - Passenger actual = repository.findFirstByOrderBySeatNumberAsc(); - - assertEquals(expected, actual); - } - - @Test - public void givenSeveralPassengersWhenFindPageSortedByThenThePassengerInTheFirstFilledSeatIsReturned() { - Passenger expected = Passenger.from("Fred", "Bloggs", 22); - - Page page = repository.findAll(PageRequest.of(0, 1, - Sort.by(Sort.Direction.ASC, "seatNumber"))); - - assertEquals(1, page.getContent().size()); - - Passenger actual = page.getContent().get(0); - assertEquals(expected, actual); - } - - @Test - public void givenPassengers_whenOrderedBySeatNumberAsc_thenCorrectOrder() { - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - - List passengers = repository.findByOrderBySeatNumberAsc(); - - assertThat(passengers, contains(fred, ricki, jill, siya, eve)); - } - - @Test - public void givenPassengers_whenFindAllWithSortBySeatNumberAsc_thenCorrectOrder() { - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - - List passengers = repository.findAll(Sort.by(Sort.Direction.ASC, "seatNumber")); - - assertThat(passengers, contains(fred, ricki, jill, siya, eve)); - } - - @Test - public void givenPassengers_whenFindByExampleDefaultMatcher_thenExpectedReturned() { - Example example = Example.of(Passenger.from("Fred", "Bloggs", null)); - - Optional actual = repository.findOne(example); - - assertTrue(actual.isPresent()); - assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get()); - } - - @Test - public void givenPassengers_whenFindByExampleCaseInsensitiveMatcher_thenExpectedReturned() { - ExampleMatcher caseInsensitiveExampleMatcher = ExampleMatcher.matchingAll().withIgnoreCase(); - Example example = Example.of(Passenger.from("fred", "bloggs", null), - caseInsensitiveExampleMatcher); - - Optional actual = repository.findOne(example); - - assertTrue(actual.isPresent()); - assertEquals(Passenger.from("Fred", "Bloggs", 22), actual.get()); - } - - @Test - public void givenPassengers_whenFindByExampleCustomMatcher_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - - ExampleMatcher customExampleMatcher = ExampleMatcher.matchingAny().withMatcher("firstName", - ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()).withMatcher("lastName", - ExampleMatcher.GenericPropertyMatchers.contains().ignoreCase()); - - Example example = Example.of(Passenger.from("e", "s", null), - customExampleMatcher); - - List passengers = repository.findAll(example); - - assertThat(passengers, contains(jill, eve, fred, siya)); - assertThat(passengers, not(contains(ricki))); - } - - @Test - public void givenPassengers_whenFindByIgnoringMatcher_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - - ExampleMatcher ignoringExampleMatcher = ExampleMatcher.matchingAny().withMatcher("lastName", - ExampleMatcher.GenericPropertyMatchers.startsWith().ignoreCase()).withIgnorePaths("firstName", "seatNumber"); - - Example example = Example.of(Passenger.from(null, "b", null), - ignoringExampleMatcher); - - List passengers = repository.findAll(example); - - assertThat(passengers, contains(fred, ricki)); - assertThat(passengers, not(contains(jill))); - assertThat(passengers, not(contains(eve))); - assertThat(passengers, not(contains(siya))); - } - - @Test - public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { - Passenger jill = Passenger.from("Jill", "Smith", 50); - Passenger eve = Passenger.from("Eve", "Jackson", 95); - Passenger fred = Passenger.from("Fred", "Bloggs", 22); - Passenger siya = Passenger.from("Siya", "Kolisi", 85); - Passenger ricki = Passenger.from("Ricki", "Bobbie", 36); - - List passengers = repository.findByFirstNameIgnoreCase("FRED"); - - assertThat(passengers, contains(fred)); - assertThat(passengers, not(contains(eve))); - assertThat(passengers, not(contains(siya))); - assertThat(passengers, not(contains(jill))); - assertThat(passengers, not(contains(ricki))); - - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java deleted file mode 100644 index 831790af95..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.baeldung.multipledb; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.Before; -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.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.Product; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) -@EnableTransactionManagement -public class ProductRepositoryIntegrationTest { - - @Autowired - private ProductRepository productRepository; - - @Before - @Transactional("productTransactionManager") - public void setUp() { - productRepository.save(Product.from(1001, "Book", 21)); - productRepository.save(Product.from(1002, "Coffee", 10)); - productRepository.save(Product.from(1003, "Jeans", 30)); - productRepository.save(Product.from(1004, "Shirt", 32)); - productRepository.save(Product.from(1005, "Bacon", 10)); - } - - @Test - public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1001, 1002) - .contains(id))); - } - - @Test - public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { - Pageable pageRequest = PageRequest.of(1, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1003, 1004) - .contains(id))); - } - - @Test - public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { - Pageable pageRequest = PageRequest.of(2, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(1)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1005) - .contains(id))); - } - - @Test - public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); - - } - - @Test - public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") - .descending()); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); - - } - - @Test - public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") - .descending() - .and(Sort.by("name"))); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(5)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); - - } - - @Test - public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - List result = productRepository.findAllByPrice(10, pageRequest); - - assertThat(result, hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1002, 1005) - .contains(id))); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java deleted file mode 100644 index 0fc9918701..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/repository/EmployeeRepositoryIntegrationTest.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.baeldung.repository; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -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 com.baeldung.boot.Application; -import com.baeldung.entity.Employee; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class EmployeeRepositoryIntegrationTest { - - private static final Employee EMPLOYEE1 = new Employee(1L, "John"); - private static final Employee EMPLOYEE2 = new Employee(2L, "Alice"); - - @Autowired - private EmployeeRepository employeeRepository; - - @Test - public void givenEmployeeEntity_whenInsertWithSave_ThenEmployeeIsPersisted() { - employeeRepository.save(EMPLOYEE1); - assertEmployeePersisted(EMPLOYEE1); - } - - @Test - public void givenEmployeeEntity_whenInsertWithSaveAndFlush_ThenEmployeeIsPersisted() { - employeeRepository.saveAndFlush(EMPLOYEE2); - assertEmployeePersisted(EMPLOYEE2); - } - - private void assertEmployeePersisted(Employee input) { - Employee employee = employeeRepository.getOne(input.getId()); - assertThat(employee).isNotNull(); - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java deleted file mode 100644 index e5ad2dd448..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.util; - -import org.testcontainers.containers.PostgreSQLContainer; - -public class BaeldungPostgresqlContainer extends PostgreSQLContainer { - - private static final String IMAGE_VERSION = "postgres:11.1"; - - private static BaeldungPostgresqlContainer container; - - - private BaeldungPostgresqlContainer() { - super(IMAGE_VERSION); - } - - public static BaeldungPostgresqlContainer getInstance() { - if (container == null) { - container = new BaeldungPostgresqlContainer(); - } - return container; - } - - @Override - public void start() { - super.start(); - System.setProperty("DB_URL", container.getJdbcUrl()); - System.setProperty("DB_USERNAME", container.getUsername()); - System.setProperty("DB_PASSWORD", container.getPassword()); - } - - @Override - public void stop() { - //do nothing, JVM handles shut down - } -} diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties deleted file mode 100644 index 4141f5668e..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-batchinserts.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.jpa.show-sql=false - -spring.jpa.properties.hibernate.jdbc.batch_size=5 -spring.jpa.properties.hibernate.order_inserts=true -spring.jpa.properties.hibernate.order_updates=true -spring.jpa.properties.hibernate.batch_versioned_data=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties deleted file mode 100644 index c3005d861f..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc-auto.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for test containers testing -spring.datasource.url=${DB_URL} -spring.datasource.username=${DB_USERNAME} -spring.datasource.password=${DB_PASSWORD} diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties deleted file mode 100644 index 3bf8693d53..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-tc.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for Test Containers testing -spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false diff --git a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties deleted file mode 100644 index f9497c8f37..0000000000 --- a/persistence-modules/spring-data-jpa-3/src/test/resources/application-test.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/README.md b/persistence-modules/spring-data-jpa-4/README.md deleted file mode 100644 index 085dfcb366..0000000000 --- a/persistence-modules/spring-data-jpa-4/README.md +++ /dev/null @@ -1,18 +0,0 @@ -### Relevant Articles: -- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) -- [LIKE Queries in Spring JPA Repositories](https://www.baeldung.com/spring-jpa-like-queries) -- [A Guide to Spring’s Open Session In View](https://www.baeldung.com/spring-open-session-in-view) -- [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management) -- [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) -- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) -- [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) -- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-4/create.sql b/persistence-modules/spring-data-jpa-4/create.sql deleted file mode 100644 index 1bbe1640a7..0000000000 --- a/persistence-modules/spring-data-jpa-4/create.sql +++ /dev/null @@ -1,2 +0,0 @@ -create table PERSON (ID int8 not null, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID)) -create table person (id int8 not null, first_name varchar(255), last_name varchar(255), primary key (id)) diff --git a/persistence-modules/spring-data-jpa-4/pom.xml b/persistence-modules/spring-data-jpa-4/pom.xml deleted file mode 100644 index 71fc21527f..0000000000 --- a/persistence-modules/spring-data-jpa-4/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - spring-data-jpa-4 - spring-data-jpa-4 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-data-jdbc - - - - mysql - mysql-connector-java - - - - org.postgresql - postgresql - - - - com.h2database - h2 - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java deleted file mode 100644 index d7a1950305..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/QueryApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.derivedquery; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class QueryApplication { - - public static void main(String[] args) { - SpringApplication.run(QueryApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java deleted file mode 100644 index 49e824f09f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/entity/User.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.baeldung.derivedquery.entity; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; -import java.time.ZonedDateTime; - -@Table(name = "users") -@Entity -public class User { - - @Id - @GeneratedValue - private Integer id; - private String name; - private Integer age; - private ZonedDateTime birthDate; - private Boolean active; - - public User() { - } - - public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) { - this.name = name; - this.age = age; - this.birthDate = birthDate; - this.active = active; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public ZonedDateTime getBirthDate() { - return birthDate; - } - - public void setBirthDate(ZonedDateTime birthDate) { - this.birthDate = birthDate; - } - - public Boolean getActive() { - return active; - } - - public void setActive(Boolean active) { - this.active = active; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java deleted file mode 100644 index e613ee1531..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.baeldung.derivedquery.repository; - -import com.baeldung.derivedquery.entity.User; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.time.ZonedDateTime; -import java.util.Collection; -import java.util.List; - -public interface UserRepository extends JpaRepository { - - List findByName(String name); - - List findByNameIs(String name); - - List findByNameEquals(String name); - - List findByNameIsNull(); - - List findByNameNot(String name); - - List findByNameIsNot(String name); - - List findByNameStartingWith(String name); - - List findByNameEndingWith(String name); - - List findByNameContaining(String name); - - List findByNameLike(String name); - - List findByAgeLessThan(Integer age); - - List findByAgeLessThanEqual(Integer age); - - List findByAgeGreaterThan(Integer age); - - List findByAgeGreaterThanEqual(Integer age); - - List findByAgeBetween(Integer startAge, Integer endAge); - - List findByBirthDateAfter(ZonedDateTime birthDate); - - List findByBirthDateBefore(ZonedDateTime birthDate); - - List findByActiveTrue(); - - List findByActiveFalse(); - - List findByAgeIn(Collection ages); - - List findByNameOrBirthDate(String name, ZonedDateTime birthDate); - - List findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active); - - List findByNameOrderByName(String name); - - List findByNameOrderByNameDesc(String name); - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java deleted file mode 100644 index 3f152a6ffc..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.elementcollection; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ElementCollectionApplication { - public static void main(String[] args) { - SpringApplication.run(ElementCollectionApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java deleted file mode 100644 index 8b98164d63..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Employee.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.elementcollection.model; - -import javax.persistence.*; -import java.util.List; -import java.util.Objects; - -@Entity -public class Employee { - @Id - private int id; - private String name; - @ElementCollection - @CollectionTable(name = "employee_phone", joinColumns = @JoinColumn(name = "employee_id")) - private List phones; - - public Employee() { - } - - public Employee(int id) { - this.id = id; - } - - public Employee(int id, String name) { - this.id = id; - this.name = name; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getPhones() { - return phones; - } - - public void setPhones(List phones) { - this.phones = phones; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Employee)) { - return false; - } - Employee user = (Employee) o; - return getId() == user.getId(); - } - - @Override - public int hashCode() { - return Objects.hash(getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java deleted file mode 100644 index d73d30c47a..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/model/Phone.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.baeldung.elementcollection.model; - -import javax.persistence.Embeddable; -import java.util.Objects; - -@Embeddable -public class Phone { - private String type; - private String areaCode; - private String number; - - public Phone() { - } - - public Phone(String type, String areaCode, String number) { - this.type = type; - this.areaCode = areaCode; - this.number = number; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getAreaCode() { - return areaCode; - } - - public void setAreaCode(String areaCode) { - this.areaCode = areaCode; - } - - public String getNumber() { - return number; - } - - public void setNumber(String number) { - this.number = number; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof Phone)) { - return false; - } - Phone phone = (Phone) o; - return getType().equals(phone.getType()) && getAreaCode().equals(phone.getAreaCode()) - && getNumber().equals(phone.getNumber()); - } - - @Override - public int hashCode() { - return Objects.hash(getType(), getAreaCode(), getNumber()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java deleted file mode 100644 index 49180c35eb..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.elementcollection.repository; - -import com.baeldung.elementcollection.model.Employee; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import javax.persistence.EntityGraph; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import java.util.HashMap; -import java.util.Map; - -@Repository -public class EmployeeRepository { - - @PersistenceContext - private EntityManager em; - - @Transactional - public void save(Employee employee) { - em.persist(employee); - } - - @Transactional - public void remove(int id) { - Employee employee = findById(id); - em.remove(employee); - } - - public Employee findById(int id) { - return em.find(Employee.class, id); - } - - public Employee findByJPQL(int id) { - return em.createQuery("SELECT u FROM Employee AS u JOIN FETCH u.phones WHERE u.id=:id", Employee.class) - .setParameter("id", id).getSingleResult(); - } - - public Employee findByEntityGraph(int id) { - EntityGraph entityGraph = em.createEntityGraph(Employee.class); - entityGraph.addAttributeNodes("name", "phones"); - Map properties = new HashMap<>(); - properties.put("javax.persistence.fetchgraph", entityGraph); - return em.find(Employee.class, id, properties); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java deleted file mode 100644 index fbc861c5fe..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/SpringBootLifecycleEventApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.lifecycleevents; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringBootLifecycleEventApplication { - public static void main(String[] args) { - SpringApplication.run(SpringBootLifecycleEventApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java deleted file mode 100644 index 26ebff42e4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/AuditTrailListener.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.lifecycleevents.model; - -import javax.persistence.PostLoad; -import javax.persistence.PostPersist; -import javax.persistence.PostRemove; -import javax.persistence.PostUpdate; -import javax.persistence.PrePersist; -import javax.persistence.PreRemove; -import javax.persistence.PreUpdate; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -public class AuditTrailListener { - private static Log log = LogFactory.getLog(AuditTrailListener.class); - - @PrePersist - @PreUpdate - @PreRemove - private void beforeAnyUpdate(User user) { - if (user.getId() == 0) { - log.info("[USER AUDIT] About to add a user"); - } else { - log.info("[USER AUDIT] About to update/delete user: " + user.getId()); - } - } - - @PostPersist - @PostUpdate - @PostRemove - private void afterAnyUpdate(User user) { - log.info("[USER AUDIT] add/update/delete complete for user: " + user.getId()); - } - - @PostLoad - private void afterLoad(User user) { - log.info("[USER AUDIT] user loaded from database: " + user.getId()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java deleted file mode 100644 index a080cb3bf2..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/model/User.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.baeldung.lifecycleevents.model; - -import javax.persistence.Entity; -import javax.persistence.EntityListeners; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.PostLoad; -import javax.persistence.PostPersist; -import javax.persistence.PostRemove; -import javax.persistence.PostUpdate; -import javax.persistence.PrePersist; -import javax.persistence.PreRemove; -import javax.persistence.PreUpdate; -import javax.persistence.Transient; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -@Entity -@EntityListeners(AuditTrailListener.class) -public class User { - private static Log log = LogFactory.getLog(User.class); - - @Id - @GeneratedValue - private int id; - - private String userName; - private String firstName; - private String lastName; - @Transient - private String fullName; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getFullName() { - return fullName; - } - - @PrePersist - public void logNewUserAttempt() { - log.info("Attempting to add new user with username: " + userName); - } - - @PostPersist - public void logNewUserAdded() { - log.info("Added user '" + userName + "' with ID: " + id); - } - - @PreRemove - public void logUserRemovalAttempt() { - log.info("Attempting to delete user: " + userName); - } - - @PostRemove - public void logUserRemoval() { - log.info("Deleted user: " + userName); - } - - @PreUpdate - public void logUserUpdateAttempt() { - log.info("Attempting to update user: " + userName); - } - - @PostUpdate - public void logUserUpdate() { - log.info("Updated user: " + userName); - } - - @PostLoad - public void logUserLoad() { - fullName = firstName + " " + lastName; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java deleted file mode 100644 index af14117ebb..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/lifecycleevents/repository/UserRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.lifecycleevents.repository; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.lifecycleevents.model.User; - -public interface UserRepository extends JpaRepository { - public User findByUserName(String userName); -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java deleted file mode 100644 index 311aea3001..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/LikeApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.like; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class LikeApplication { - - public static void main(String[] args) { - SpringApplication.run(LikeApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java deleted file mode 100644 index bba8bd35c4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/model/Movie.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.like.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Movie { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE) - private Long id; - private String title; - private String director; - private String rating; - private int duration; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getDirector() { - return director; - } - - public void setDirector(String director) { - this.director = director; - } - - public String getRating() { - return rating; - } - - public void setRating(String rating) { - this.rating = rating; - } - - public int getDuration() { - return duration; - } - - public void setDuration(int duration) { - this.duration = duration; - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java deleted file mode 100644 index 241bdd3306..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/like/repository/MovieRepository.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.like.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; - -import com.baeldung.like.model.Movie; - -public interface MovieRepository extends CrudRepository { - - List findByTitleContaining(String title); - - List findByTitleLike(String title); - - List findByTitleContains(String title); - - List findByTitleIsContaining(String title); - - List findByRatingStartsWith(String rating); - - List findByDirectorEndsWith(String director); - - List findByTitleContainingIgnoreCase(String title); - - List findByRatingNotContaining(String rating); - - List findByDirectorNotLike(String director); - - @Query("SELECT m FROM Movie m WHERE m.title LIKE %:title%") - List searchByTitleLike(@Param("title") String title); - - @Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%") - List searchByRatingStartsWith(String rating); - - //Escaping works in SpringBoot >= 2.4.1 - //@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}") - @Query("SELECT m FROM Movie m WHERE m.director LIKE %:#{[0]}") - List searchByDirectorEndsWith(String director); -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java deleted file mode 100644 index cfb6e67c2c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/Person.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.namingstrategy; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; - -@Entity -public class Person { - @Id - private Long id; - - private String firstName; - - private String lastName; - - public Person() {} - - public Person(Long id, String firstName, String lastName) { - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - } - - public Long id() { - return id; - } - - public String firstName() { - return firstName; - } - - public String lastName() { - return lastName; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java deleted file mode 100644 index 3c7c25bbcb..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/PersonRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.springframework.data.jpa.repository.JpaRepository; - -public interface PersonRepository extends JpaRepository { -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java deleted file mode 100644 index 16b01e50e3..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class QuotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toLowerCase(), true); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java deleted file mode 100644 index 3cb62aa5a2..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class QuotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toUpperCase(), true); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java deleted file mode 100644 index f223015db8..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class SpringDataJpaNamingConventionApplication { -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java deleted file mode 100644 index 69e96aee27..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class UnquotedLowerCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toLowerCase(), false); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java deleted file mode 100644 index cb87af10f4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; - -public class UnquotedUpperCaseNamingStrategy extends SpringPhysicalNamingStrategy { - @Override - protected Identifier getIdentifier(String name, boolean quoted, JdbcEnvironment jdbcEnvironment) { - return new Identifier(name.toUpperCase(), false); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java deleted file mode 100644 index 4cfcf83e56..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/OsivApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.osiv; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class OsivApplication { - - public static void main(String[] args) { - SpringApplication.run(OsivApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java deleted file mode 100644 index 98f4e379d4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/model/BasicUser.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.baeldung.osiv.model; - -import javax.persistence.*; -import java.util.Set; - -@Entity -@Table(name = "users") -public class BasicUser { - - @Id - @GeneratedValue - private Long id; - - private String username; - - @ElementCollection - private Set permissions; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java deleted file mode 100644 index e8d5955d91..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/repository/BasicUserRepository.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.baeldung.osiv.repository; - -import java.util.Optional; - -import org.springframework.data.jpa.repository.EntityGraph; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.osiv.model.BasicUser; - -@Repository -@Transactional -public interface BasicUserRepository extends JpaRepository { - - @EntityGraph(attributePaths = "permissions") - Optional findDetailedByUsername(String username); - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java deleted file mode 100644 index 1de51678d5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/SimpleUserService.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.osiv.service; - -import java.util.Optional; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.osiv.model.BasicUser; -import com.baeldung.osiv.repository.BasicUserRepository; - -@Service -public class SimpleUserService implements UserService { - - private final BasicUserRepository userRepository; - - public SimpleUserService(BasicUserRepository userRepository) { - this.userRepository = userRepository; - } - - @Override - @Transactional(readOnly = true) - public Optional findOne(String username) { - return userRepository.findDetailedByUsername(username); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java deleted file mode 100644 index 3d089fa41b..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/service/UserService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.osiv.service; - -import com.baeldung.osiv.model.BasicUser; - -import java.util.Optional; - -public interface UserService { - Optional findOne(String username); -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java deleted file mode 100644 index fd2882c2d5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/DetailedUserDto.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.osiv.web; - -import com.baeldung.osiv.model.BasicUser; - -import java.util.Set; - -public class DetailedUserDto { - - private Long id; - private String username; - private Set permissions; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public Set getPermissions() { - return permissions; - } - - public void setPermissions(Set permissions) { - this.permissions = permissions; - } - - public static DetailedUserDto fromEntity(BasicUser user) { - DetailedUserDto detailed = new DetailedUserDto(); - detailed.setId(user.getId()); - detailed.setUsername(user.getUsername()); - detailed.setPermissions(user.getPermissions()); - - return detailed; - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java deleted file mode 100644 index 5466b95166..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/osiv/web/UserController.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.osiv.web; - -import com.baeldung.osiv.service.UserService; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/users") -public class UserController { - - private final UserService userService; - - public UserController(UserService userService) { - this.userService = userService; - } - - @GetMapping("/{username}") - public ResponseEntity findOne(@PathVariable String username) { - return userService.findOne(username) - .map(DetailedUserDto::fromEntity) - .map(ResponseEntity::ok) - .orElse(ResponseEntity.notFound().build()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java deleted file mode 100644 index 5f05764e21..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/StoredProcedureApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.storedprocedure; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class StoredProcedureApplication { - - public static void main(String[] args) { - SpringApplication.run(StoredProcedureApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java deleted file mode 100644 index 6aef600d01..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/controller/CarController.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.storedprocedure.controller; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import com.baeldung.storedprocedure.entity.Car; -import com.baeldung.storedprocedure.service.CarService; - -@RestController -public class CarController { - @Autowired - private CarService carService; - - @GetMapping(path = "/modelcount") - public long getTotalCarsByModel(@RequestParam("model") String model) { - return carService.getTotalCarsByModel(model); - } - - @GetMapping(path = "/modelcountP") - public long getTotalCarsByModelProcedureName(@RequestParam("model") String model) { - return carService.getTotalCarsByModelProcedureName(model); - } - - @GetMapping(path = "/modelcountV") - public long getTotalCarsByModelVaue(@RequestParam("model") String model) { - return carService.getTotalCarsByModelValue(model); - } - - @GetMapping(path = "/modelcountEx") - public long getTotalCarsByModelExplicit(@RequestParam("model") String model) { - return carService.getTotalCarsByModelExplicit(model); - } - - @GetMapping(path = "/modelcountEn") - public long getTotalCarsByModelEntity(@RequestParam("model") String model) { - return carService.getTotalCarsByModelEntity(model); - } - - @GetMapping(path = "/carsafteryear") - public List findCarsAfterYear(@RequestParam("year") Integer year) { - return carService.findCarsAfterYear(year); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java deleted file mode 100644 index 2817c25ff7..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/entity/Car.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.storedprocedure.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedStoredProcedureQuery; -import javax.persistence.StoredProcedureParameter; -import javax.persistence.ParameterMode; - -@Entity -@NamedStoredProcedureQuery(name = "Car.getTotalCardsbyModelEntity", procedureName = "GET_TOTAL_CARS_BY_MODEL", parameters = { - @StoredProcedureParameter(mode = ParameterMode.IN, name = "model_in", type = String.class), - @StoredProcedureParameter(mode = ParameterMode.OUT, name = "count_out", type = Integer.class) }) - -public class Car { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column - private long id; - - @Column - private String model; - - @Column - private Integer year; - - public long getId() { - return id; - } - - public String getModel() { - return model; - } - - public Integer getYear() { - return year; - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java deleted file mode 100644 index 3d9428628e..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/repository/CarRepository.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.storedprocedure.repository; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.jpa.repository.query.Procedure; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.baeldung.storedprocedure.entity.Car; - -@Repository -public interface CarRepository extends JpaRepository { - - @Procedure - int GET_TOTAL_CARS_BY_MODEL(String model); - - @Procedure("GET_TOTAL_CARS_BY_MODEL") - int getTotalCarsByModel(String model); - - @Procedure(procedureName = "GET_TOTAL_CARS_BY_MODEL") - int getTotalCarsByModelProcedureName(String model); - - @Procedure(value = "GET_TOTAL_CARS_BY_MODEL") - int getTotalCarsByModelValue(String model); - - @Procedure(name = "Car.getTotalCardsbyModelEntity") - int getTotalCarsByModelEntiy(@Param("model_in") String model); - - @Query(value = "CALL FIND_CARS_AFTER_YEAR(:year_in);", nativeQuery = true) - List findCarsAfterYear(@Param("year_in") Integer year_in); - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java deleted file mode 100644 index 104f46e324..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/storedprocedure/service/CarService.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.storedprocedure.service; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.storedprocedure.entity.Car; -import com.baeldung.storedprocedure.repository.CarRepository; - -@Service -public class CarService { - @Autowired - private CarRepository carRepository; - - public int getTotalCarsByModel(String model) { - return carRepository.getTotalCarsByModel(model); - } - - public int getTotalCarsByModelProcedureName(String model) { - return carRepository.getTotalCarsByModelProcedureName(model); - } - - public int getTotalCarsByModelValue(String model) { - return carRepository.getTotalCarsByModelValue(model); - } - - public int getTotalCarsByModelExplicit(String model) { - return carRepository.GET_TOTAL_CARS_BY_MODEL(model); - } - - public int getTotalCarsByModelEntity(String model) { - return carRepository.getTotalCarsByModelEntiy(model); - } - - public List findCarsAfterYear(Integer year) { - return carRepository.findCarsAfterYear(year); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java deleted file mode 100644 index 4c982c91e9..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/TxApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.tx; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class TxApplication { - - public static void main(String[] args) { - SpringApplication.run(TxApplication.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java b/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java deleted file mode 100644 index 921a1e9275..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/java/com/baeldung/tx/model/Payment.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.tx.model; - -import javax.persistence.*; - -@Entity -public class Payment { - - @Id - @GeneratedValue - private Long id; - - private Long amount; - - @Column(unique = true) - private String referenceNumber; - - @Enumerated(EnumType.STRING) - private State state; - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getAmount() { - return amount; - } - - public void setAmount(Long amount) { - this.amount = amount; - } - - public String getReferenceNumber() { - return referenceNumber; - } - - public void setReferenceNumber(String referenceNumber) { - this.referenceNumber = referenceNumber; - } - - public State getState() { - return state; - } - - public void setState(State state) { - this.state = state; - } - - public enum State { - STARTED, FAILED, SUCCESSFUL - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties deleted file mode 100644 index 65d7b0bf29..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.jpa.show-sql=true -#MySql -#spring.datasource.url=jdbc:mysql://localhost:3306/baeldung -#spring.datasource.username=baeldung -#spring.datasource.password=baeldung \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql b/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql deleted file mode 100644 index bb4ab2a86e..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/main/resources/car-mysql.sql +++ /dev/null @@ -1,27 +0,0 @@ -DROP TABLE IF EXISTS car; - -CREATE TABLE car (id int(10) NOT NULL AUTO_INCREMENT, - model varchar(50) NOT NULL, - year int(4) NOT NULL, - PRIMARY KEY (id)); - -INSERT INTO car (model, year) VALUES ('BMW', 2000); -INSERT INTO car (model, year) VALUES ('BENZ', 2010); -INSERT INTO car (model, year) VALUES ('PORCHE', 2005); -INSERT INTO car (model, year) VALUES ('PORCHE', 2004); - -DELIMITER $$ - -DROP PROCEDURE IF EXISTS FIND_CARS_AFTER_YEAR$$ -CREATE PROCEDURE FIND_CARS_AFTER_YEAR(IN year_in INT) -BEGIN - SELECT * FROM car WHERE year >= year_in ORDER BY year; -END$$ - -DROP PROCEDURE IF EXISTS GET_TOTAL_CARS_BY_MODEL$$ -CREATE PROCEDURE GET_TOTAL_CARS_BY_MODEL(IN model_in VARCHAR(50), OUT count_out INT) -BEGIN - SELECT COUNT(*) into count_out from car WHERE model = model_in; -END$$ - -DELIMITER ; diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index 2a6e166b88..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.baeldung.derivedquery.repository; - -import com.baeldung.derivedquery.QueryApplication; -import com.baeldung.derivedquery.entity.User; -import org.junit.After; -import org.junit.Before; -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.time.ZonedDateTime; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = QueryApplication.class) -public class UserRepositoryIntegrationTest { - - private static final String USER_NAME_ADAM = "Adam"; - private static final String USER_NAME_EVE = "Eve"; - private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now(); - - @Autowired - private UserRepository userRepository; - - @Before - public void setUp() { - - User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true); - User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false); - User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true); - User user4 = new User(null, 30, BIRTHDATE, false); - - userRepository.saveAll(Arrays.asList(user1, user2, user3, user4)); - } - - @After - public void tearDown() { - - userRepository.deleteAll(); - } - - @Test - public void whenFindByName_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size()); - } - - @Test - public void whenFindByNameIsNull_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameIsNull().size()); - } - - @Test - public void whenFindByNameNot_thenReturnsCorrectResult() { - - assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName()); - } - - @Test - public void whenFindByNameStartingWith_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByNameStartingWith("A").size()); - } - - @Test - public void whenFindByNameEndingWith_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameEndingWith("e").size()); - } - - @Test - public void whenByNameContaining_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameContaining("v").size()); - } - - - @Test - public void whenByNameLike_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByNameEndingWith("m").size()); - } - - @Test - public void whenByAgeLessThan_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByAgeLessThan(25).size()); - } - - - @Test - public void whenByAgeLessThanEqual_thenReturnsCorrectResult() { - - assertEquals(3, userRepository.findByAgeLessThanEqual(25).size()); - } - - @Test - public void whenByAgeGreaterThan_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByAgeGreaterThan(25).size()); - } - - @Test - public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size()); - } - - @Test - public void whenByAgeBetween_thenReturnsCorrectResult() { - - assertEquals(4, userRepository.findByAgeBetween(20, 30).size()); - } - - @Test - public void whenByBirthDateAfter_thenReturnsCorrectResult() { - - final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); - assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size()); - } - - @Test - public void whenByBirthDateBefore_thenReturnsCorrectResult() { - - final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); - assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size()); - } - - @Test - public void whenByActiveTrue_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByActiveTrue().size()); - } - - @Test - public void whenByActiveFalse_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByActiveFalse().size()); - } - - - @Test - public void whenByAgeIn_thenReturnsCorrectResult() { - - final List ages = Arrays.asList(20, 25); - assertEquals(3, userRepository.findByAgeIn(ages).size()); - } - - @Test - public void whenByNameOrBirthDate() { - - assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size()); - } - - @Test - public void whenByNameOrBirthDateAndActive() { - - assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size()); - } - - @Test - public void whenByNameOrderByName() { - - assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size()); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java deleted file mode 100644 index 306798aa68..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.elementcollection; - -import com.baeldung.elementcollection.model.Employee; -import com.baeldung.elementcollection.model.Phone; -import com.baeldung.elementcollection.repository.EmployeeRepository; -import org.junit.After; -import org.junit.Before; -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 org.springframework.transaction.annotation.Transactional; - -import java.util.Arrays; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ElementCollectionApplication.class) -public class ElementCollectionIntegrationTest { - - @Autowired - private EmployeeRepository employeeRepository; - - @Before - public void init() { - Employee employee = new Employee(1, "Fred"); - employee.setPhones( - Arrays.asList(new Phone("work", "+55", "99999-9999"), new Phone("home", "+55", "98888-8888"))); - employeeRepository.save(employee); - } - - @After - public void clean() { - employeeRepository.remove(1); - } - - @Test(expected = org.hibernate.LazyInitializationException.class) - public void whenAccessLazyCollection_thenThrowLazyInitializationException() { - Employee employee = employeeRepository.findById(1); - assertThat(employee.getPhones().size(), is(2)); - } - - @Test - public void whenUseJPAQL_thenFetchResult() { - Employee employee = employeeRepository.findByJPQL(1); - assertThat(employee.getPhones().size(), is(2)); - } - - @Test - public void whenUseEntityGraph_thenFetchResult() { - Employee employee = employeeRepository.findByEntityGraph(1); - assertThat(employee.getPhones().size(), is(2)); - } - - @Test - @Transactional - public void whenUseTransaction_thenFetchResult() { - Employee employee = employeeRepository.findById(1); - assertThat(employee.getPhones().size(), is(2)); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java deleted file mode 100644 index cc96b638ab..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/like/MovieRepositoryIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.like; - -import com.baeldung.like.model.Movie; -import com.baeldung.like.repository.MovieRepository; -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.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; - -@RunWith(SpringRunner.class) -@Sql(scripts = { "/test-movie-data.sql" }) -@SpringBootTest(classes = LikeApplication.class) -@Sql(scripts = "/test-movie-cleanup.sql", executionPhase = AFTER_TEST_METHOD) -public class MovieRepositoryIntegrationTest { - @Autowired - private MovieRepository movieRepository; - - @Test - public void givenPartialTitle_WhenFindByTitleContaining_ThenMoviesShouldReturn() { - List results = movieRepository.findByTitleContaining("in"); - assertEquals(3, results.size()); - - results = movieRepository.findByTitleLike("%in%"); - assertEquals(3, results.size()); - - results = movieRepository.findByTitleIsContaining("in"); - assertEquals(3, results.size()); - - results = movieRepository.findByTitleContains("in"); - assertEquals(3, results.size()); - } - - @Test - public void givenStartOfRating_WhenFindByRatingStartsWith_ThenMoviesShouldReturn() { - List results = movieRepository.findByRatingStartsWith("PG"); - assertEquals(6, results.size()); - } - - @Test - public void givenLastName_WhenFindByDirectorEndsWith_ThenMoviesShouldReturn() { - List results = movieRepository.findByDirectorEndsWith("Burton"); - assertEquals(1, results.size()); - } - - @Test - public void givenPartialTitle_WhenFindByTitleContainingIgnoreCase_ThenMoviesShouldReturn() { - List results = movieRepository.findByTitleContainingIgnoreCase("the"); - assertEquals(2, results.size()); - } - - @Test - public void givenPartialTitle_WhenSearchByTitleLike_ThenMoviesShouldReturn() { - List results = movieRepository.searchByTitleLike("in"); - assertEquals(3, results.size()); - } - - @Test - public void givenStartOfRating_SearchFindByRatingStartsWith_ThenMoviesShouldReturn() { - List results = movieRepository.searchByRatingStartsWith("PG"); - assertEquals(6, results.size()); - } - - @Test - public void givenLastName_WhenSearchByDirectorEndsWith_ThenMoviesShouldReturn() { - List results = movieRepository.searchByDirectorEndsWith("Burton"); - assertEquals(1, results.size()); - } - - @Test - public void givenPartialRating_findByRatingNotContaining_ThenMoviesShouldReturn() { - List results = movieRepository.findByRatingNotContaining("PG"); - assertEquals(1, results.size()); - } - - @Test - public void givenPartialDirector_WhenFindByDirectorNotLike_ThenMoviesShouldReturn() { - List results = movieRepository.findByDirectorNotLike("An%"); - assertEquals(5, results.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 71a4dbda3f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-lower-case-naming-strategy.properties") -class QuotedLowerCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index 6b1c984600..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") -class QuotedLowerCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index f819327a5c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-upper-case-naming-strategy.properties") -class QuotedUpperCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenException(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index bd23b81b4b..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") -class QuotedUpperCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 1850fea173..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("spring-physical-naming-strategy.properties") -class SpringPhysicalNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Unexpected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java deleted file mode 100644 index e26ebb148d..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") -class SpringPhysicalNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndSpringNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndSpringNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 6311c42e93..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-lower-case-naming-strategy.properties") -class UnquotedLowerCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Unexpected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index 033a213cf5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") -class UnquotedLowerCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndLowerCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java deleted file mode 100644 index 7af8001854..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-upper-case-naming-strategy.properties") -class UnquotedUpperCaseNamingStrategyH2IntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Expected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java deleted file mode 100644 index 0151e7ece4..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.baeldung.namingstrategy; - -import org.hibernate.exception.SQLGrammarException; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.TestPropertySource; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) -@TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") -class UnquotedUpperCaseNamingStrategyPostgresLiveTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private PersonRepository personRepository; - - @BeforeEach - void insertPeople() { - personRepository.saveAll(Arrays.asList( - new Person(1L, "John", "Doe"), - new Person(2L, "Jane", "Doe"), - new Person(3L, "Ted", "Mosby") - )); - } - - @ParameterizedTest - @ValueSource(strings = {"person", "PERSON", "Person"}) - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonUnquoted_thenResult(String tableName) { - Query query = entityManager.createNativeQuery("select * from " + tableName); - - // Expected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedUpperCase_thenException() { - Query query = entityManager.createNativeQuery("select * from \"PERSON\""); - - // Unexpected result - assertThrows(SQLGrammarException.class, query::getResultStream); - } - - @Test - void givenPeopleAndUpperCaseNamingStrategy_whenQueryPersonQuotedLowerCase_thenResult() { - Query query = entityManager.createNativeQuery("select * from \"person\""); - - // Unexpected result - List result = (List) query.getResultStream() - .map(this::fromDatabase) - .collect(Collectors.toList()); - - assertThat(result).isNotEmpty(); - } - - public Person fromDatabase(Object databaseRow) { - Object[] typedDatabaseRow = (Object[]) databaseRow; - - return new Person( - ((BigInteger) typedDatabaseRow[0]).longValue(), - (String) typedDatabaseRow[1], - (String) typedDatabaseRow[2] - ); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java deleted file mode 100644 index 350b67e1c9..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/osiv/UserControllerIntegrationTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.osiv; - -import com.baeldung.osiv.model.BasicUser; -import com.baeldung.osiv.repository.BasicUserRepository; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Arrays; -import java.util.HashSet; - -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@SpringBootTest -@AutoConfigureMockMvc -@ActiveProfiles("test") -@ContextConfiguration(classes = OsivApplication.class) -class UserControllerIntegrationTest { - - @Autowired - private BasicUserRepository userRepository; - - @Autowired - private MockMvc mockMvc; - - @BeforeEach - void setUp() { - BasicUser user = new BasicUser(); - user.setUsername("root"); - user.setPermissions(new HashSet<>(Arrays.asList("PERM_READ", "PERM_WRITE"))); - - userRepository.save(user); - } - - @Test - void givenTheUserExists_WhenOsivIsEnabled_ThenLazyInitWorkEverywhere() throws Exception { - mockMvc.perform(get("/users/root")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.username").value("root")) - .andExpect(jsonPath("$.permissions", containsInAnyOrder("PERM_READ", "PERM_WRITE"))); - } - - @AfterEach - void flushDb() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java deleted file mode 100644 index 01551348c9..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/com/baeldung/tx/ManualTransactionIntegrationTest.java +++ /dev/null @@ -1,152 +0,0 @@ -package com.baeldung.tx; - -import com.baeldung.tx.model.Payment; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; -import org.springframework.transaction.support.TransactionTemplate; - -import javax.persistence.EntityManager; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED; - -@DataJpaTest -@ActiveProfiles("test") -@Transactional(propagation = NOT_SUPPORTED) -class ManualTransactionIntegrationTest { - - @Autowired - private PlatformTransactionManager transactionManager; - - @Autowired - private EntityManager entityManager; - - private TransactionTemplate transactionTemplate; - - @BeforeEach - void setUp() { - transactionTemplate = new TransactionTemplate(transactionManager); - } - - @AfterEach - void flushDb() { - transactionTemplate.execute(status -> entityManager - .createQuery("delete from Payment") - .executeUpdate()); - } - - @Test - void givenAPayment_WhenNotDuplicate_ThenShouldCommit() { - Long id = transactionTemplate.execute(status -> { - Payment payment = new Payment(); - payment.setAmount(1000L); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - - return payment.getId(); - }); - - Payment payment = entityManager.find(Payment.class, id); - assertThat(payment).isNotNull(); - } - - @Test - void givenAPayment_WhenMarkAsRollback_ThenShouldRollback() { - transactionTemplate.execute(status -> { - Payment payment = new Payment(); - payment.setAmount(1000L); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - status.setRollbackOnly(); - - return payment.getId(); - }); - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).isEmpty(); - } - - @Test - void givenTwoPayments_WhenRefIsDuplicate_ThenShouldRollback() { - try { - transactionTemplate.execute(s -> { - Payment first = new Payment(); - first.setAmount(1000L); - first.setReferenceNumber("Ref-1"); - first.setState(Payment.State.SUCCESSFUL); - - Payment second = new Payment(); - second.setAmount(2000L); - second.setReferenceNumber("Ref-1"); - second.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(first); - entityManager.persist(second); - - return "Ref-1"; - }); - } catch (Exception ignored) { - } - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).isEmpty(); - } - - @Test - void givenAPayment_WhenNotExpectingAnyResult_ThenShouldCommit() { - transactionTemplate.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - Payment payment = new Payment(); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - } - }); - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).hasSize(1); - } - - @Test - void givenAPayment_WhenUsingTxManager_ThenShouldCommit() { - DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); - definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - definition.setTimeout(3); - - TransactionStatus status = transactionManager.getTransaction(definition); - try { - Payment payment = new Payment(); - payment.setReferenceNumber("Ref-1"); - payment.setState(Payment.State.SUCCESSFUL); - - entityManager.persist(payment); - transactionManager.commit(status); - } catch (Exception ex) { - transactionManager.rollback(status); - } - - assertThat(entityManager - .createQuery("select p from Payment p", Payment.class) - .getResultList()).hasSize(1); - } - -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java deleted file mode 100644 index 078f437474..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/java/lifecycleevents/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package lifecycleevents; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.After; -import org.junit.Before; -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 com.baeldung.lifecycleevents.SpringBootLifecycleEventApplication; -import com.baeldung.lifecycleevents.model.User; -import com.baeldung.lifecycleevents.repository.UserRepository; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = SpringBootLifecycleEventApplication.class) -public class UserRepositoryIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Before - public void setup() { - User user = new User(); - user.setFirstName("Jane"); - user.setLastName("Smith"); - user.setUserName("jsmith123"); - userRepository.save(user); - } - - @After - public void cleanup() { - userRepository.deleteAll(); - } - - @Test - public void whenNewUserProvided_userIsAdded() { - User user = new User(); - user.setFirstName("John"); - user.setLastName("Doe"); - user.setUserName("jdoe123"); - user = userRepository.save(user); - assertTrue(user.getId() > 0); - } - - @Test - public void whenUserNameProvided_userIsLoaded() { - User user = userRepository.findByUserName("jsmith123"); - assertNotNull(user); - assertEquals("jsmith123", user.getUserName()); - } - - @Test - public void whenExistingUserProvided_userIsUpdated() { - User user = userRepository.findByUserName("jsmith123"); - user.setFirstName("Joe"); - user = userRepository.save(user); - assertEquals("Joe", user.getFirstName()); - } - - @Test - public void whenExistingUserDeleted_userIsDeleted() { - User user = userRepository.findByUserName("jsmith123"); - userRepository.delete(user); - user = userRepository.findByUserName("jsmith123"); - assertNull(user); - } - - @Test - public void whenExistingUserLoaded_fullNameIsAvailable() { - String expectedFullName = "Jane Smith"; - User user = userRepository.findByUserName("jsmith123"); - assertEquals(expectedFullName, user.getFullName()); - } -} diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties deleted file mode 100644 index f9497c8f37..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/application-test.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:jpa3 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties deleted file mode 100644 index 04b29de41f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-lower-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties deleted file mode 100644 index 6643c12c8a..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:quoted-lower-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties deleted file mode 100644 index 36898d5b4f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/quoted-upper-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties deleted file mode 100644 index 6d56d58749..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:quoted-upper-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.QuotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties deleted file mode 100644 index 706b12b1b6..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/spring-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties deleted file mode 100644 index c9a0c6f24c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:spring-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=default-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties deleted file mode 100644 index b22472bd8f..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-lower-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties deleted file mode 100644 index 8083515b4b..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:unquoted-lower-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedLowerCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties deleted file mode 100644 index da03a0d7b5..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:postgresql://localhost:5432/unquoted-upper-case-strategy -spring.datasource.username=postgres -spring.datasource.password=root - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties deleted file mode 100644 index d1b63e008c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.datasource.url=jdbc:h2:mem:unquoted-upper-case-strategy -spring.datasource.username=sa -spring.datasource.password= - -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.hibernate.naming.physical-strategy=com.baeldung.namingstrategy.UnquotedUpperCaseNamingStrategy -#spring.jpa.properties.javax.persistence.schema-generation.create-source=metadata -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=upper-case-naming-strategy-ddl.sql \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql b/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql deleted file mode 100644 index 90aa15307c..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-cleanup.sql +++ /dev/null @@ -1 +0,0 @@ -DELETE FROM Movie; \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql b/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql deleted file mode 100644 index 37f8e4fe64..0000000000 --- a/persistence-modules/spring-data-jpa-4/src/test/resources/test-movie-data.sql +++ /dev/null @@ -1,7 +0,0 @@ -INSERT INTO movie(id, title, director, rating, duration) VALUES(1, 'Godzilla: King of the Monsters', ' Michael Dougherty', 'PG-13', 132); -INSERT INTO movie(id, title, director, rating, duration) VALUES(2, 'Avengers: Endgame', 'Anthony Russo', 'PG-13', 181); -INSERT INTO movie(id, title, director, rating, duration) VALUES(3, 'Captain Marvel', 'Anna Boden', 'PG-13', 123); -INSERT INTO movie(id, title, director, rating, duration) VALUES(4, 'Dumbo', 'Tim Burton', 'PG', 112); -INSERT INTO movie(id, title, director, rating, duration) VALUES(5, 'Booksmart', 'Olivia Wilde', 'R', 102); -INSERT INTO movie(id, title, director, rating, duration) VALUES(6, 'Aladdin', 'Guy Ritchie', 'PG', 128); -INSERT INTO movie(id, title, director, rating, duration) VALUES(7, 'The Sun Is Also a Star', 'Ry Russo-Young', 'PG-13', 100); diff --git a/persistence-modules/spring-data-jpa-5/README.md b/persistence-modules/spring-data-jpa-5/README.md deleted file mode 100644 index 0b78ced66c..0000000000 --- a/persistence-modules/spring-data-jpa-5/README.md +++ /dev/null @@ -1,15 +0,0 @@ -### Relevant Articles: - -- [Spring JPA @Embedded and @EmbeddedId](https://www.baeldung.com/spring-jpa-embedded-method-parameters) -- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema) -- [Partial Data Update with Spring Data](https://www.baeldung.com/spring-data-partial-update) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator - diff --git a/persistence-modules/spring-data-jpa-5/pom.xml b/persistence-modules/spring-data-jpa-5/pom.xml deleted file mode 100644 index db58a16062..0000000000 --- a/persistence-modules/spring-data-jpa-5/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - 4.0.0 - spring-data-jpa-5 - spring-data-jpa-5 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - org.springframework.boot - spring-boot-starter-data-jdbc - - - - org.springframework.boot - spring-boot-starter-cache - - - - com.h2database - h2 - - - - org.mapstruct - mapstruct-jdk8 - ${mapstruct.version} - provided - - - - - - src/main/java - - - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - - - org.mapstruct - mapstruct-processor - 1.3.1.Final - - - - - - - - - 2.1.9.RELEASE - com.baeldung.springdatageode.app.ClientCacheApp - 1.1.1.RELEASE - 2.1.9.RELEASE - 1.3.1.Final - - - diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java deleted file mode 100644 index 52f06058aa..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/BookApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.composite; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class BookApplication { - - public static void main(String[] args) { - SpringApplication.run(BookApplication.class); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java deleted file mode 100644 index e4f1727654..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/Book.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.baeldung.composite.entity; - -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; - -@Entity -public class Book { - - @EmbeddedId - private BookId id; - private String genre; - private Integer price; - - public Book() { - } - - public Book(String author, String name, String genre, Integer price) { - BookId id = new BookId(author, name); - this.id = id; - this.genre = genre; - this.price = price; - } - - public BookId getId() { - return id; - } - - public void setId(BookId id) { - this.id = id; - } - - public String getGenre() { - return genre; - } - - public void setGenre(String genre) { - this.genre = genre; - } - - public Integer getPrice() { - return price; - } - - public void setPrice(Integer price) { - this.price = price; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java deleted file mode 100644 index 1524452412..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/entity/BookId.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.baeldung.composite.entity; - -import javax.persistence.Embeddable; -import java.io.Serializable; -import java.util.Objects; - -@Embeddable -public class BookId implements Serializable { - - private String author; - private String name; - - public BookId() { - } - - public BookId(String author, String name) { - this.author = author; - this.name = name; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - BookId bookId = (BookId) o; - return Objects.equals(author, bookId.author) && Objects.equals(name, bookId.name); - } - - @Override - public int hashCode() { - return Objects.hash(author, name); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java deleted file mode 100644 index d5993eaf79..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/composite/repository/BookRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.composite.repository; - -import com.baeldung.composite.entity.Book; -import com.baeldung.composite.entity.BookId; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface BookRepository extends JpaRepository { - - List findByIdName(String name); - - List findByIdAuthor(String author); - - List findByGenre(String genre); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java deleted file mode 100644 index a750fcadf7..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/PartialUpdateApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.partialupdate; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class PartialUpdateApplication { - - public static void main(String[] args) { - SpringApplication.run(PartialUpdateApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java deleted file mode 100644 index 352e361bd9..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/ContactPhone.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.partialupdate.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class ContactPhone { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - public long id; - @Column(nullable=false) - public long customerId; - public String phone; - - @Override - public String toString() { - return phone; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java deleted file mode 100644 index b19d0b7952..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/Customer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.partialupdate.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - -@Entity -public class Customer { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - public long id; - public String name; - public String phone; - //... - public String phone99; - - @Override public String toString() { - return String.format("Customer %s, Phone: %s", - this.name, this.phone); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java deleted file mode 100644 index 0ecf206d9a..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerDto.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.partialupdate.model; - -public class CustomerDto { - private long id; - public String name; - public String phone; - //... - private String phone99; - - public CustomerDto(long id) { - this.id = id; - } - - public CustomerDto(Customer c) { - this.id = c.id; - this.name = c.name; - this.phone = c.phone; - } - - public long getId() { - return this.id; - } - - public Customer convertToEntity() { - Customer c = new Customer(); - c.id = id; - c.name = name; - c.phone = phone; - return c; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java deleted file mode 100644 index dd053a963d..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/model/CustomerStructured.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.partialupdate.model; - -import java.util.List; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; - -@Entity -public class CustomerStructured { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - public long id; - public String name; - @OneToMany(fetch = FetchType.EAGER, targetEntity = ContactPhone.class, mappedBy = "customerId") - public List contactPhones; - - @Override public String toString() { - return String.format("Customer %s, Phone: %s", - this.name, this.contactPhones.stream() - .map(e -> e.toString()).reduce("", String::concat)); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java deleted file mode 100644 index 4668181e05..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/ContactPhoneRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.partialupdate.repository; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.partialupdate.model.ContactPhone; - -@Repository -public interface ContactPhoneRepository extends CrudRepository { - ContactPhone findById(long id); - ContactPhone findByCustomerId(long id); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java deleted file mode 100644 index 43e61df8ab..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.partialupdate.repository; - -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import com.baeldung.partialupdate.model.Customer; - -@Repository -public interface CustomerRepository extends CrudRepository { - Customer findById(long id); - - @Modifying - @Query("update Customer u set u.phone = :phone where u.id = :id") - void updatePhone(@Param(value = "id") long id, @Param(value = "phone") String phone); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java deleted file mode 100644 index 0f9fd1e92e..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/repository/CustomerStructuredRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.partialupdate.repository; - -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.partialupdate.model.CustomerStructured; - -@Repository -public interface CustomerStructuredRepository extends CrudRepository { - CustomerStructured findById(long id); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java deleted file mode 100644 index 9da97a7775..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/service/CustomerService.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.partialupdate.service; - -import javax.transaction.Transactional; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.baeldung.partialupdate.model.ContactPhone; -import com.baeldung.partialupdate.model.Customer; -import com.baeldung.partialupdate.model.CustomerDto; -import com.baeldung.partialupdate.model.CustomerStructured; -import com.baeldung.partialupdate.repository.ContactPhoneRepository; -import com.baeldung.partialupdate.repository.CustomerRepository; -import com.baeldung.partialupdate.repository.CustomerStructuredRepository; -import com.baeldung.partialupdate.util.CustomerMapper; - -@Service -@Transactional -public class CustomerService { - - @Autowired - CustomerRepository repo; - @Autowired - CustomerStructuredRepository repo2; - @Autowired - ContactPhoneRepository repo3; - @Autowired - CustomerMapper mapper; - - public Customer getCustomer(long id) { - return repo.findById(id); - } - - public void updateCustomerWithCustomQuery(long id, String phone) { - repo.updatePhone(id, phone); - } - - public Customer addCustomer(String name) { - Customer myCustomer = new Customer(); - myCustomer.name = name; - repo.save(myCustomer); - return myCustomer; - } - - public Customer updateCustomer(long id, String phone) { - Customer myCustomer = repo.findById(id); - myCustomer.phone = phone; - repo.save(myCustomer); - return myCustomer; - } - - public Customer addCustomer(CustomerDto dto) { - Customer myCustomer = new Customer(); - mapper.updateCustomerFromDto(dto, myCustomer); - repo.save(myCustomer); - return myCustomer; - } - - public Customer updateCustomer(CustomerDto dto) { - Customer myCustomer = repo.findById(dto.getId()); - mapper.updateCustomerFromDto(dto, myCustomer); - repo.save(myCustomer); - return myCustomer; - } - - public CustomerStructured addCustomerStructured(String name) { - CustomerStructured myCustomer = new CustomerStructured(); - myCustomer.name = name; - repo2.save(myCustomer); - return myCustomer; - } - - public void addCustomerPhone(long customerId, String phone) { - ContactPhone myPhone = new ContactPhone(); - myPhone.phone = phone; - myPhone.customerId = customerId; - repo3.save(myPhone); - } - - public CustomerStructured updateCustomerStructured(long id, String name) { - CustomerStructured myCustomer = repo2.findById(id); - myCustomer.name = name; - repo2.save(myCustomer); - return myCustomer; - } - -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java deleted file mode 100644 index 8a666e3e6c..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/partialupdate/util/CustomerMapper.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.partialupdate.util; - -import org.mapstruct.BeanMapping; -import org.mapstruct.Mapper; -import org.mapstruct.MappingTarget; -import org.mapstruct.NullValuePropertyMappingStrategy; - -import com.baeldung.partialupdate.model.Customer; -import com.baeldung.partialupdate.model.CustomerDto; - -@Mapper(componentModel = "spring") -public interface CustomerMapper { - @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) - void updateCustomerFromDto(CustomerDto dto, @MappingTarget Customer entity); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java deleted file mode 100644 index 547992a6c1..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/AccountApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.schemageneration; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class AccountApplication { - - public static void main(String[] args) { - SpringApplication.run(AccountApplication.class, args); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java deleted file mode 100644 index 7d69d65705..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/HibernateUtil.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.schemageneration; - -import com.baeldung.schemageneration.model.Account; -import com.baeldung.schemageneration.model.AccountSetting; -import org.hibernate.boot.Metadata; -import org.hibernate.boot.MetadataSources; -import org.hibernate.boot.registry.StandardServiceRegistry; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.Environment; -import org.hibernate.tool.hbm2ddl.SchemaExport; -import org.hibernate.tool.schema.TargetType; - -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -public class HibernateUtil { - - /** - * Generates database create commands for the specified entities using Hibernate native API, SchemaExport. - * Creation commands are exported into the create.sql file. - */ - public static void generateSchema() { - Map settings = new HashMap<>(); - settings.put(Environment.URL, "jdbc:h2:mem:schema"); - - StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); - - MetadataSources metadataSources = new MetadataSources(serviceRegistry); - metadataSources.addAnnotatedClass(Account.class); - metadataSources.addAnnotatedClass(AccountSetting.class); - Metadata metadata = metadataSources.buildMetadata(); - - SchemaExport schemaExport = new SchemaExport(); - schemaExport.setFormat(true); - schemaExport.setOutputFile("create.sql"); - schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java deleted file mode 100644 index 785e275e26..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/Account.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.schemageneration.model; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import java.util.ArrayList; -import java.util.List; - -@Entity -@Table(name = "accounts") -public class Account { - - @Id - @GeneratedValue - private Long id; - - @Column(nullable = false, length = 100) - private String name; - - @Column(name = "email_address") - private String emailAddress; - - @OneToMany(mappedBy = "account", cascade = CascadeType.ALL) - private List accountSettings = new ArrayList<>(); - - public Account() { - } - - public Account(String name, String emailAddress) { - this.name = name; - this.emailAddress = emailAddress; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmailAddress() { - return emailAddress; - } - - public void setEmailAddress(String emailAddress) { - this.emailAddress = emailAddress; - } - - public List getAccountSettings() { - return accountSettings; - } - - public void setAccountSettings(List accountSettings) { - this.accountSettings = accountSettings; - } - - public void addAccountSetting(AccountSetting setting) { - this.accountSettings.add(setting); - setting.setAccount(this); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java deleted file mode 100644 index 61e43894a8..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.schemageneration.model; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; - -@Entity -@Table(name = "account_settings") -public class AccountSetting { - - @Id - @GeneratedValue - private Long id; - - @Column(name = "name", nullable = false) - private String settingName; - - @Column(name = "value", nullable = false) - private String settingValue; - - @ManyToOne() - @JoinColumn(name ="account_id", nullable = false) - private Account account; - - public AccountSetting() { - } - - public AccountSetting(String settingName, String settingValue) { - this.settingName = settingName; - this.settingValue = settingValue; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getSettingName() { - return settingName; - } - - public void setSettingName(String settingName) { - this.settingName = settingName; - } - - public String getSettingValue() { - return settingValue; - } - - public void setSettingValue(String settingValue) { - this.settingValue = settingValue; - } - - public Account getAccount() { - return account; - } - - public void setAccount(Account account) { - this.account = account; - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java deleted file mode 100644 index dc57ffe6d3..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.schemageneration.repository; - -import com.baeldung.schemageneration.model.Account; -import org.springframework.data.repository.CrudRepository; - -public interface AccountRepository extends CrudRepository { - Account findByName(String name); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java b/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java deleted file mode 100644 index c2b8ff7398..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.schemageneration.repository; - -import com.baeldung.schemageneration.model.AccountSetting; -import org.springframework.data.repository.CrudRepository; - -public interface AccountSettingRepository extends CrudRepository { - AccountSetting findByAccountId(Long accountId); -} diff --git a/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties deleted file mode 100644 index f55ad438ff..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/main/resources/application.properties +++ /dev/null @@ -1,13 +0,0 @@ - -spring.datasource.url=jdbc:h2:mem:baeldung - -# JPA-Schema-Generation -# Use below configuration to generate database schema create commands based on the entity models -# and export them into the create.sql file -#spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=create.sql -#spring.jpa.properties.javax.persistence.schema-generation.scripts.create-source=metadata -#spring.jpa.properties.hibernate.format_sql=true - -spring.jpa.show-sql=true - diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java deleted file mode 100644 index 9d25acbd96..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/composite/repository/BookRepositoryIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.composite.repository; - -import com.baeldung.composite.BookApplication; -import com.baeldung.composite.entity.Book; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -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.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = BookApplication.class) -public class BookRepositoryIntegrationTest { - - public static final String JAVA_101 = "Java101"; - public static final String JANE = "Jane"; - public static final String TECH = "Tech"; - @Autowired - BookRepository repository; - - @Before - public void setUp() { - Book book1 = new Book("John", JAVA_101, TECH, 20); - Book book2 = new Book(JANE, JAVA_101, "Arch", 25); - Book book3 = new Book(JANE, "Scala101", TECH, 23); - - repository.saveAll(Arrays.asList(book1, book2, book3)); - } - - @After - public void tearDown() { - repository.deleteAll(); - } - - @Test - public void testFindByName() { - List books = repository.findByIdName(JAVA_101); - - assertEquals(2, books.size()); - } - - @Test - public void testFindByAuthor() { - List books = repository.findByIdAuthor(JANE); - - assertEquals(2, books.size()); - } - - @Test - public void testFindByGenre() { - List books = repository.findByGenre(TECH); - - assertEquals(2, books.size()); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java deleted file mode 100644 index 874e18c4ad..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/partialupdate/PartialUpdateUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.partialupdate; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -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 com.baeldung.partialupdate.model.Customer; -import com.baeldung.partialupdate.model.CustomerDto; -import com.baeldung.partialupdate.model.CustomerStructured; -import com.baeldung.partialupdate.service.CustomerService; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = PartialUpdateApplication.class) -public class PartialUpdateUnitTest { - - @Autowired - CustomerService service; - - @Test - public void givenCustomer_whenUpdate_thenSuccess() { - Customer myCustomer = service.addCustomer("John"); - myCustomer = service.updateCustomer(myCustomer.id, "+00"); - assertEquals("+00", myCustomer.phone); - } - - @Test - public void givenCustomer_whenUpdateWithQuery_thenSuccess() { - Customer myCustomer = service.addCustomer("John"); - service.updateCustomerWithCustomQuery(myCustomer.id, "+88"); - myCustomer = service.getCustomer(myCustomer.id); - assertEquals("+88", myCustomer.phone); - } - - @Test - public void givenCustomerDto_whenUpdateWithMapper_thenSuccess() { - CustomerDto dto = new CustomerDto(new Customer()); - dto.name = "Johnny"; - Customer entity = service.addCustomer(dto); - - CustomerDto dto2 = new CustomerDto(entity.id); - dto2.phone = "+44"; - entity = service.updateCustomer(dto2); - - assertEquals("Johnny", entity.name); - } - - @Test - public void givenCustomerStructured_whenUpdateCustomerPhone_thenSuccess() { - CustomerStructured myCustomer = service.addCustomerStructured("John"); - assertEquals(null, myCustomer.contactPhones); - - service.addCustomerPhone(myCustomer.id, "+44"); - myCustomer = service.updateCustomerStructured(myCustomer.id, "Mr. John"); - - assertNotEquals(null, myCustomer.contactPhones); - assertEquals(1, myCustomer.contactPhones.size()); - } -} diff --git a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java deleted file mode 100644 index 86a7671fe4..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.schemageneration; - -import com.baeldung.schemageneration.model.Account; -import com.baeldung.schemageneration.model.AccountSetting; -import com.baeldung.schemageneration.repository.AccountRepository; -import com.baeldung.schemageneration.repository.AccountSettingRepository; -import org.junit.After; -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.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AccountApplication.class) -public class AccountRepositoryIntegrationTest { - - private static final String USER_NAME = "Eduard"; - private static final String USER_EMAIL_ADDRESS = "eduard@gmx.com"; - private static final String ACCOUNT_SETTING_NAME = "Timezone"; - private static final String ACCOUNT_SETTING_VALUE = "UTC+02"; - - @Autowired - private AccountRepository accountRepository; - - @Autowired - private AccountSettingRepository accountSettingRepository; - - @After - public void tearDown() { - accountRepository.deleteAll(); - } - - @Test - public void givenNewAccount_whenSave_thenSuccess() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - accountRepository.save(account); - - assertEquals(1, accountRepository.count()); - } - - @Test - public void givenSavedAccount_whenFindByName_thenFound() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - accountRepository.save(account); - - Account accountFound = accountRepository.findByName(USER_NAME); - - assertNotNull(accountFound); - assertEquals(USER_NAME, accountFound.getName()); - assertEquals(USER_EMAIL_ADDRESS, accountFound.getEmailAddress()); - } - - @Test - public void givenSavedAccount_whenAccountSettingIsAdded_thenPersisted() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - account.addAccountSetting(new AccountSetting(ACCOUNT_SETTING_NAME, ACCOUNT_SETTING_VALUE)); - accountRepository.save(account); - - Account accountFound = accountRepository.findByName(USER_NAME); - assertNotNull(accountFound); - AccountSetting accountSetting = accountSettingRepository.findByAccountId(accountFound.getId()); - - assertNotNull(accountSetting); - assertEquals(ACCOUNT_SETTING_NAME, accountSetting.getSettingName()); - assertEquals(ACCOUNT_SETTING_VALUE, accountSetting.getSettingValue()); - } - -} diff --git a/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties b/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties deleted file mode 100644 index e3d39fe1e2..0000000000 --- a/persistence-modules/spring-data-jpa-5/src/test/resources/application-test.properties +++ /dev/null @@ -1,3 +0,0 @@ -spring.jpa.hibernate.ddl-auto=update -spring.datasource.url=jdbc:h2:mem:baeldung - diff --git a/persistence-modules/spring-data-jpa/README.md b/persistence-modules/spring-data-jpa/README.md deleted file mode 100644 index 1c43edf42b..0000000000 --- a/persistence-modules/spring-data-jpa/README.md +++ /dev/null @@ -1,25 +0,0 @@ -========= - -## Spring Data JPA Example Project - -### Relevant Articles: -- [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases) -- [Spring Data JPA – Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories) -- [An Advanced Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging-advanced) -- [Spring Data Annotations](https://www.baeldung.com/spring-data-annotations) -- [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8) -- [A Simple Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging) -- [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) -- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) -- [DDD Aggregates and @DomainEvents](https://www.baeldung.com/spring-data-ddd) -- [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator - diff --git a/persistence-modules/spring-data-jpa/pom.xml b/persistence-modules/spring-data-jpa/pom.xml deleted file mode 100644 index ddd7e17dcd..0000000000 --- a/persistence-modules/spring-data-jpa/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - spring-data-jpa - spring-data-jpa - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.hibernate - hibernate-ehcache - - - org.hibernate - hibernate-envers - - - - com.h2database - h2 - - - - - org.testcontainers - postgresql - ${testcontainers.postgresql.version} - test - - - - org.postgresql - postgresql - - - - - org.springframework.security - spring-security-test - test - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-test - test - - - - com.google.guava - guava - ${guava.version} - - - - - com.baeldung.boot.Application - 1.10.6 - 42.2.5 - 21.0 - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java deleted file mode 100644 index c66921a3ca..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/Application.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.boot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import com.baeldung.boot.daos.impl.ExtendedRepositoryImpl; - -@SpringBootApplication -@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java deleted file mode 100644 index 76d5887030..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/config/PersistenceConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.baeldung.boot.services.IBarService; -import com.baeldung.boot.services.impl.BarSpringDataJpaService; - -@Configuration -@Profile("!tc") -@EnableTransactionManagement -@EnableJpaAuditing -public class PersistenceConfiguration { - - @Bean - public IBarService barSpringDataJpaService() { - return new BarSpringDataJpaService(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java deleted file mode 100644 index 73397ad42e..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ArticleRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.Article; - -import java.util.Date; -import java.util.List; - -public interface ArticleRepository extends JpaRepository { - - List
findAllByPublicationDate(Date publicationDate); - - List
findAllByPublicationTimeBetween(Date publicationTimeStart, - Date publicationTimeEnd); - - @Query("select a from Article a where a.creationDateTime <= :creationDateTime") - List
findAllWithCreationDateTimeBefore( - @Param("creationDateTime") Date creationDateTime); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java deleted file mode 100644 index 0aebe34921..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Item; - -@Repository -public interface CustomItemRepository { - - void deleteCustom(Item entity); - - Item findItemById(Long id); - - void findThenDelete(Long id); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java deleted file mode 100644 index 832d61408c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/CustomItemTypeRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.ItemType; - -@Repository -public interface CustomItemTypeRepository { - - void deleteCustom(ItemType entity); - - void findThenDelete(Long id); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java deleted file mode 100644 index adb2af4320..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.daos; - -import java.io.Serializable; -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.repository.NoRepositoryBean; - -@NoRepositoryBean -public interface ExtendedRepository extends JpaRepository { - - List findByAttributeContainsText(String attributeName, String text); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java deleted file mode 100644 index c9b0192536..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ExtendedStudentRepository.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.domain.Student; - -public interface ExtendedStudentRepository extends ExtendedRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java deleted file mode 100644 index 921fabe3fb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IBarCrudRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.repository.CrudRepository; - -import com.baeldung.boot.domain.Bar; - -import java.io.Serializable; - -public interface IBarCrudRepository extends CrudRepository { - // -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java deleted file mode 100644 index d537772076..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/IFooDao.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.Foo; - -public interface IFooDao extends JpaRepository { - - @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") - Foo retrieveByName(@Param("name") String name); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java deleted file mode 100644 index 606f3993d5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/InventoryRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.repository.CrudRepository; - -import com.baeldung.boot.domain.MerchandiseEntity; - -public interface InventoryRepository extends CrudRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java deleted file mode 100644 index 413c09e968..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ItemTypeRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.ItemType; - -@Repository -public interface ItemTypeRepository extends JpaRepository, CustomItemTypeRepository, CustomItemRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java deleted file mode 100644 index 697ce295d0..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/LocationRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.baeldung.boot.daos; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Location; - -@Repository -public interface LocationRepository extends JpaRepository { -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java deleted file mode 100644 index 3a2ea3cda5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/ReadOnlyLocationRepository.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.boot.daos; - -import java.util.Optional; - -import org.springframework.data.repository.Repository; - -import com.baeldung.boot.domain.Location; - -@org.springframework.stereotype.Repository -public interface ReadOnlyLocationRepository extends Repository { - - Optional findById(Long id); - - Location save(Location location); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java deleted file mode 100644 index ae13f75f66..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/StoreRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.daos; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.domain.Store; - -@Repository -public interface StoreRepository extends JpaRepository { - List findStoreByLocationId(Long locationId); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java deleted file mode 100644 index 820a2cdd41..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemRepositoryImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import javax.persistence.EntityManager; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.daos.CustomItemRepository; -import com.baeldung.boot.domain.Item; - -@Repository -public class CustomItemRepositoryImpl implements CustomItemRepository { - - @Autowired - private EntityManager entityManager; - - @Override - public void deleteCustom(Item item) { - entityManager.remove(item); - } - - @Override - public Item findItemById(Long id) { - return entityManager.find(Item.class, id); - } - - @Override - public void findThenDelete(Long id) { - final Item item = entityManager.find(Item.class, id); - entityManager.remove(item); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java deleted file mode 100644 index e057f36b26..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/CustomItemTypeRepositoryImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import javax.persistence.EntityManager; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import com.baeldung.boot.daos.CustomItemTypeRepository; -import com.baeldung.boot.domain.ItemType; - -@Repository -public class CustomItemTypeRepositoryImpl implements CustomItemTypeRepository { - - @Autowired - private EntityManager entityManager; - - @Override - public void deleteCustom(ItemType itemType) { - entityManager.remove(itemType); - } - - @Override - public void findThenDelete(Long id) { - ItemType itemTypeToDelete = entityManager.find(ItemType.class, id); - entityManager.remove(itemTypeToDelete); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java deleted file mode 100644 index fbe6695844..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/impl/ExtendedRepositoryImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.boot.daos.impl; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import javax.transaction.Transactional; - -import org.springframework.data.jpa.repository.support.JpaEntityInformation; -import org.springframework.data.jpa.repository.support.SimpleJpaRepository; - -import com.baeldung.boot.daos.ExtendedRepository; - -public class ExtendedRepositoryImpl extends SimpleJpaRepository implements ExtendedRepository { - - private EntityManager entityManager; - - public ExtendedRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) { - super(entityInformation, entityManager); - this.entityManager = entityManager; - } - - @Transactional - public List findByAttributeContainsText(String attributeName, String text) { - CriteriaBuilder builder = entityManager.getCriteriaBuilder(); - CriteriaQuery query = builder.createQuery(getDomainClass()); - Root root = query.from(getDomainClass()); - query.select(root).where(builder.like(root. get(attributeName), "%" + text + "%")); - TypedQuery q = entityManager.createQuery(query); - return q.getResultList(); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java deleted file mode 100644 index e102754c18..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/PossessionRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.boot.daos.user; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.boot.domain.Possession; - -public interface PossessionRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java deleted file mode 100644 index 53f692ff28..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepository.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.baeldung.boot.daos.user; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; - -import com.baeldung.boot.domain.User; - -import java.time.LocalDate; -import java.util.Collection; -import java.util.List; -import java.util.stream.Stream; - -public interface UserRepository extends JpaRepository , UserRepositoryCustom{ - - Stream findAllByName(String name); - - @Query("SELECT u FROM User u WHERE u.status = 1") - Collection findAllActiveUsers(); - - @Query("select u from User u where u.email like '%@gmail.com'") - List findUsersWithGmailAddress(); - - @Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true) - Collection findAllActiveUsersNative(); - - @Query("SELECT u FROM User u WHERE u.status = ?1") - User findUserByStatus(Integer status); - - @Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true) - User findUserByStatusNative(Integer status); - - @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") - User findUserByStatusAndName(Integer status, String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name); - - @Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true) - User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name); - - @Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name") - User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName); - - @Query("SELECT u FROM User u WHERE u.name like ?1%") - User findUserByNameLike(String name); - - @Query("SELECT u FROM User u WHERE u.name like :name%") - User findUserByNameLikeNamedParam(@Param("name") String name); - - @Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true) - User findUserByNameLikeNative(String name); - - @Query(value = "SELECT u FROM User u") - List findAllUsers(Sort sort); - - @Query(value = "SELECT u FROM User u ORDER BY id") - Page findAllUsersWithPagination(Pageable pageable); - - @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) - Page findAllUsersWithPaginationNative(Pageable pageable); - - @Modifying - @Query("update User u set u.status = :status where u.name = :name") - int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); - - @Modifying - @Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNative(Integer status, String name); - - @Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true) - @Modifying - void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active); - - @Modifying - @Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true) - int updateUserSetStatusForNameNativePostgres(Integer status, String name); - - @Query(value = "SELECT u FROM User u WHERE u.name IN :names") - List findUserByNameList(@Param("names") Collection names); - - void deleteAllByCreationDateAfter(LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("update User u set u.active = false where u.lastLoginDate < :date") - void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query("delete User u where u.active = false") - int deleteDeactivatedUsers(); - - @Modifying(clearAutomatically = true, flushAutomatically = true) - @Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true) - void addDeletedColumn(); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java deleted file mode 100644 index c586b54027..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustom.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.function.Predicate; - -import com.baeldung.boot.domain.User; - -public interface UserRepositoryCustom { - List findUserByEmails(Set emails); - - List findAllUsersByPredicates(Collection> predicates); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java deleted file mode 100644 index 63a743b6b5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/daos/user/UserRepositoryCustomImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.boot.daos.user; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - -import com.baeldung.boot.domain.User; - -public class UserRepositoryCustomImpl implements UserRepositoryCustom { - - @PersistenceContext - private EntityManager entityManager; - - @Override - public List findUserByEmails(Set emails) { - CriteriaBuilder cb = entityManager.getCriteriaBuilder(); - CriteriaQuery query = cb.createQuery(User.class); - Root user = query.from(User.class); - - Path emailPath = user.get("email"); - - List predicates = new ArrayList<>(); - for (String email : emails) { - - predicates.add(cb.like(emailPath, email)); - - } - query.select(user) - .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); - - return entityManager.createQuery(query) - .getResultList(); - } - - @Override - public List findAllUsersByPredicates(Collection> predicates) { - List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); - Stream allUsersStream = allUsers.stream(); - for (java.util.function.Predicate predicate : predicates) { - allUsersStream = allUsersStream.filter(predicate); - } - - return allUsersStream.collect(Collectors.toList()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java deleted file mode 100644 index e435f4c85c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Transient; - -import org.springframework.context.ApplicationEventPublisher; - -@Entity -class Aggregate { - @Transient - private ApplicationEventPublisher eventPublisher; - @Id - private long id; - - private Aggregate() { - } - - Aggregate(long id, ApplicationEventPublisher eventPublisher) { - this.id = id; - this.eventPublisher = eventPublisher; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "DomainEntity [id=" + id + "]"; - } - - void domainOperation() { - // some business logic - if (eventPublisher != null) { - eventPublisher.publishEvent(new DomainEvent()); - } - } - - long getId() { - return id; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java deleted file mode 100644 index 08f61db812..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import java.util.ArrayList; -import java.util.Collection; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Transient; - -import org.springframework.data.domain.AfterDomainEventPublication; -import org.springframework.data.domain.DomainEvents; - -@Entity -public class Aggregate2 { - @Transient - private final Collection domainEvents; - @Id - @GeneratedValue - private long id; - - public Aggregate2() { - domainEvents = new ArrayList<>(); - } - - @AfterDomainEventPublication - public void clearEvents() { - domainEvents.clear(); - } - - public void domainOperation() { - // some domain operation - domainEvents.add(new DomainEvent()); - } - - @DomainEvents - public Collection events() { - return domainEvents; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java deleted file mode 100644 index 7f09c410fc..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate2Repository.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.data.repository.CrudRepository; - -public interface Aggregate2Repository extends CrudRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java deleted file mode 100644 index f664322a59..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; - -import org.springframework.data.domain.AbstractAggregateRoot; - -@Entity -public class Aggregate3 extends AbstractAggregateRoot { - @Id - @GeneratedValue - private long id; - - public void domainOperation() { - // some domain operation - registerEvent(new DomainEvent()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java deleted file mode 100644 index 93f50bb5cf..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/Aggregate3Repository.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.data.repository.CrudRepository; - -/** - * @author goobar - * - */ -public interface Aggregate3Repository extends CrudRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java deleted file mode 100644 index 1c2d3884bf..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/AggregateRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.data.repository.CrudRepository; - -public interface AggregateRepository extends CrudRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java deleted file mode 100644 index 34cf21463b..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DddConfig.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.PropertySource; - -@SpringBootConfiguration -@EnableAutoConfiguration -@PropertySource("classpath:/ddd.properties") -public class DddConfig { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java deleted file mode 100644 index e7626e742d..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainEvent.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -class DomainEvent { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java deleted file mode 100644 index 80aa5ca6cb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/ddd/event/DomainService.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import javax.transaction.Transactional; - -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.stereotype.Service; - -@Service -public class DomainService { - private final ApplicationEventPublisher eventPublisher; - private final AggregateRepository repository; - - public DomainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { - this.repository = repository; - this.eventPublisher = eventPublisher; - } - - @Transactional - public void serviceDomainOperation(long entityId) { - repository.findById(entityId) - .ifPresent(entity -> { - entity.domainOperation(); - repository.save(entity); - eventPublisher.publishEvent(new DomainEvent()); - }); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java deleted file mode 100644 index de4dbed1a0..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Article.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; -import java.util.Date; - -@Entity -public class Article { - - @Id - @GeneratedValue - private Integer id; - @Temporal(TemporalType.DATE) - private Date publicationDate; - @Temporal(TemporalType.TIME) - private Date publicationTime; - @Temporal(TemporalType.TIMESTAMP) - private Date creationDateTime; - - public Integer getId() { - return id; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java deleted file mode 100644 index 35d1903801..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Bar.java +++ /dev/null @@ -1,220 +0,0 @@ -package com.baeldung.boot.domain; - -import com.google.common.collect.Sets; -import org.hibernate.annotations.OrderBy; -import org.hibernate.envers.Audited; -import org.jboss.logging.Logger; -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; - -import javax.persistence.*; -import java.io.Serializable; -import java.util.Date; -import java.util.Set; - -@Entity -@NamedQuery(name = "Bar.findAll", query = "SELECT b FROM Bar b") -@Audited -@EntityListeners(AuditingEntityListener.class) -public class Bar implements Serializable { - - private static Logger logger = Logger.getLogger(Bar.class); - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private int id; - - @Column(name = "name") - private String name; - @OneToMany(mappedBy = "bar", cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @OrderBy(clause = "NAME DESC") - // @NotAudited - private Set fooSet = Sets.newHashSet(); - @Column(name = "operation") - private String operation; - @Column(name = "timestamp") - private long timestamp; - @Column(name = "created_date", updatable = false, nullable = false) - @CreatedDate - private long createdDate; - @Column(name = "modified_date") - @LastModifiedDate - private long modifiedDate; - @Column(name = "created_by") - @CreatedBy - private String createdBy; - @Column(name = "modified_by") - @LastModifiedBy - private String modifiedBy; - - public Bar() { - super(); - } - - public Bar(final String name) { - super(); - - this.name = name; - } - - public Set getFooSet() { - return fooSet; - } - - // API - - public void setFooSet(final Set fooSet) { - this.fooSet = fooSet; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public OPERATION getOperation() { - return OPERATION.parse(operation); - } - - public void setOperation(final String operation) { - this.operation = operation; - } - - public void setOperation(final OPERATION operation) { - this.operation = operation.getValue(); - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(final long timestamp) { - this.timestamp = timestamp; - } - - public long getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(final long createdDate) { - this.createdDate = createdDate; - } - - public long getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(final long modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(final String createdBy) { - this.createdBy = createdBy; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(final String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Bar other = (Bar) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Bar [name=").append(name).append("]"); - return builder.toString(); - } - - @PrePersist - public void onPrePersist() { - logger.info("@PrePersist"); - audit(OPERATION.INSERT); - } - - @PreUpdate - public void onPreUpdate() { - logger.info("@PreUpdate"); - audit(OPERATION.UPDATE); - } - - @PreRemove - public void onPreRemove() { - logger.info("@PreRemove"); - audit(OPERATION.DELETE); - } - - private void audit(final OPERATION operation) { - setOperation(operation); - setTimestamp((new Date()).getTime()); - } - - public enum OPERATION { - INSERT, UPDATE, DELETE; - private String value; - - OPERATION() { - value = toString(); - } - - public static OPERATION parse(final String value) { - OPERATION operation = null; - for (final OPERATION op : OPERATION.values()) { - if (op.getValue().equals(value)) { - operation = op; - break; - } - } - return operation; - } - - public String getValue() { - return value; - } - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java deleted file mode 100644 index 5030e5600b..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Foo.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.baeldung.boot.domain; - -import org.hibernate.envers.Audited; - -import javax.persistence.*; -import java.io.Serializable; - -@NamedNativeQueries({@NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class)}) -@Entity -@Audited -// @Proxy(lazy = false) -public class Foo implements Serializable { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private long id; - - @Column(name = "name", nullable = false) - private String name; - - @ManyToOne(targetEntity = Bar.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar = new Bar(); - - public Foo() { - super(); - } - - public Foo(final String name) { - super(); - this.name = name; - } - - // - - public Bar getBar() { - return bar; - } - - public void setBar(final Bar bar) { - this.bar = bar; - } - - public long getId() { - return id; - } - - public void setId(final long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - // - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final Foo other = (Foo) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Foo [name=").append(name).append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java deleted file mode 100644 index 8ac06af15a..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Item.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.baeldung.boot.domain; - -import java.math.BigDecimal; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; - -@Entity -public class Item { - - private String color; - private String grade; - - @Id - private Long id; - - @ManyToOne - private ItemType itemType; - - private String name; - private BigDecimal price; - @ManyToOne - private Store store; - - public String getColor() { - return color; - } - - public String getGrade() { - return grade; - } - - public Long getId() { - return id; - } - - public ItemType getItemType() { - return itemType; - } - - public String getName() { - return name; - } - - public BigDecimal getPrice() { - return price; - } - - public Store getStore() { - return store; - } - - public void setColor(String color) { - this.color = color; - } - - public void setGrade(String grade) { - this.grade = grade; - } - - public void setId(Long id) { - this.id = id; - } - - public void setItemType(ItemType itemType) { - this.itemType = itemType; - } - - public void setName(String name) { - this.name = name; - } - - public void setPrice(BigDecimal price) { - this.price = price; - } - - public void setStore(Store store) { - this.store = store; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java deleted file mode 100644 index 8a52a9847c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/ItemType.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.baeldung.boot.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; - -@Entity -public class ItemType { - - @Id - private Long id; - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "ITEM_TYPE_ID") - private List items = new ArrayList<>(); - - private String name; - - public Long getId() { - return id; - } - - public List getItems() { - return items; - } - - public String getName() { - return name; - } - - public void setId(Long id) { - this.id = id; - } - - public void setItems(List items) { - this.items = items; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java deleted file mode 100644 index 1901f43c0a..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/KVTag.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Embeddable; - -@Embeddable -public class KVTag { - private String key; - private String value; - - public KVTag() { - } - - public KVTag(String key, String value) { - super(); - this.key = key; - this.value = value; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java deleted file mode 100644 index 9c1b93d551..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Location.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.boot.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OneToMany; - -@Entity -public class Location { - - private String city; - private String country; - @Id - private Long id; - - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "LOCATION_ID") - private List stores = new ArrayList<>(); - - public String getCity() { - return city; - } - - public String getCountry() { - return country; - } - - public Long getId() { - return id; - } - - public List getStores() { - return stores; - } - - public void setCity(String city) { - this.city = city; - } - - public void setCountry(String country) { - this.country = country; - } - - public void setId(Long id) { - this.id = id; - } - - public void setStores(List stores) { - this.stores = stores; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java deleted file mode 100644 index e94c23de86..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/MerchandiseEntity.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import java.math.BigDecimal; - -@Entity -public class MerchandiseEntity { - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private Long id; - - private String title; - - private BigDecimal price; - - private String brand; - - public MerchandiseEntity() { - } - - public MerchandiseEntity(String title, BigDecimal price) { - this.title = title; - this.price = price; - } - - public Long getId() { - return id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public BigDecimal getPrice() { - return price; - } - - public void setPrice(BigDecimal price) { - this.price = price; - } - - public String getBrand() { - return brand; - } - - public void setBrand(String brand) { - this.brand = brand; - } - - @Override - public String toString() { - return "MerchandiseEntity{" + - "id=" + id + - ", title='" + title + '\'' + - ", price=" + price + - ", brand='" + brand + '\'' + - '}'; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java deleted file mode 100644 index f13491ad82..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Possession.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; -import com.baeldung.boot.domain.Possession; - -@Entity -@Table -public class Possession { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public Possession() { - super(); - } - - public Possession(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Possession other = (Possession) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java deleted file mode 100644 index 0933a3e6af..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/SkillTag.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.Embeddable; - -@Embeddable -public class SkillTag { - private String name; - private int value; - - public SkillTag() { - } - - public SkillTag(String name, int value) { - super(); - this.name = name; - this.value = value; - } - - public int getValue() { - return value; - } - - public void setValue(int value) { - this.value = value; - } - - public String getName() { - return name; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java deleted file mode 100644 index 5b4b831cc7..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Store.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.baeldung.boot.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; - -@Entity -public class Store { - - private Boolean active; - @Id - private Long id; - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "STORE_ID") - private List items = new ArrayList<>(); - private Long itemsSold; - - @ManyToOne - private Location location; - - private String name; - - public Boolean getActive() { - return active; - } - - public Long getId() { - return id; - } - - public List getItems() { - return items; - } - - public Long getItemsSold() { - return itemsSold; - } - - public Location getLocation() { - return location; - } - - public String getName() { - return name; - } - - public void setActive(Boolean active) { - this.active = active; - } - - public void setId(Long id) { - this.id = id; - } - - public void setItems(List items) { - this.items = items; - } - - public void setItemsSold(Long itemsSold) { - this.itemsSold = itemsSold; - } - - public void setLocation(Location location) { - this.location = location; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java deleted file mode 100644 index 1003167cc7..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/Student.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.Id; -import java.util.ArrayList; -import java.util.List; - -@Entity -public class Student { - - @Id - private long id; - private String name; - - @ElementCollection - private List tags = new ArrayList<>(); - - @ElementCollection - private List skillTags = new ArrayList<>(); - - @ElementCollection - private List kvTags = new ArrayList<>(); - - public Student() { - } - - public Student(long id, String name) { - super(); - this.id = id; - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags.addAll(tags); - } - - public List getSkillTags() { - return skillTags; - } - - public void setSkillTags(List skillTags) { - this.skillTags.addAll(skillTags); - } - - public List getKVTags() { - return this.kvTags; - } - - public void setKVTags(List kvTags) { - this.kvTags.addAll(kvTags); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java deleted file mode 100644 index cca00e52a2..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/domain/User.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.baeldung.boot.domain; - -import javax.persistence.*; - -import java.time.LocalDate; -import java.util.List; -import java.util.Objects; - -@Entity -@Table(name = "users") -public class User { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String name; - private LocalDate creationDate; - private LocalDate lastLoginDate; - private boolean active; - private int age; - @Column(unique = true, nullable = false) - private String email; - private Integer status; - @OneToMany - List possessionList; - - public User() { - super(); - } - - public User(String name, LocalDate creationDate,String email, Integer status) { - this.name = name; - this.creationDate = creationDate; - this.email = email; - this.status = status; - this.active = true; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - public LocalDate getCreationDate() { - return creationDate; - } - - public List getPossessionList() { - return possessionList; - } - - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - User user = (User) o; - return id == user.id && - age == user.age && - Objects.equals(name, user.name) && - Objects.equals(creationDate, user.creationDate) && - Objects.equals(email, user.email) && - Objects.equals(status, user.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, name, creationDate, age, email, status); - } - - public LocalDate getLastLoginDate() { - return lastLoginDate; - } - - public void setLastLoginDate(LocalDate lastLoginDate) { - this.lastLoginDate = lastLoginDate; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java deleted file mode 100644 index 8054cbba59..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IBarService.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.boot.services; - -import com.baeldung.boot.domain.Bar; - -public interface IBarService extends IOperations { - // -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java deleted file mode 100644 index 871cccdd45..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IFooService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.boot.services; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; - -import com.baeldung.boot.domain.Foo; - -public interface IFooService extends IOperations { - - Foo retrieveByName(String name); - - Page findPaginated(Pageable pageable); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java deleted file mode 100644 index ec2b866b6f..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/IOperations.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.baeldung.boot.services; - -import org.springframework.data.domain.Page; - -import java.io.Serializable; -import java.util.List; - -public interface IOperations { - - T findOne(final long id); - - List findAll(); - - Page findPaginated(int page, int size); - - // write - - T create(final T entity); - - T update(final T entity); - - void delete(final T entity); - - void deleteById(final long entityId); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java deleted file mode 100644 index f88d018bbb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractService.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.baeldung.boot.services.IOperations; -import com.google.common.collect.Lists; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.io.Serializable; -import java.util.List; - -@Transactional -public abstract class AbstractService implements IOperations { - - // read - one - - @Override - @Transactional(readOnly = true) - public T findOne(final long id) { - return getDao().findById(id).orElse(null); - } - - // read - all - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public Page findPaginated(final int page, final int size) { - return getDao().findAll(PageRequest.of(page, size)); - } - - // write - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().deleteById(entityId); - } - - protected abstract PagingAndSortingRepository getDao(); - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java deleted file mode 100644 index a73a6bd7fc..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/AbstractSpringDataJpaService.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.baeldung.boot.services.IOperations; -import com.google.common.collect.Lists; -import org.springframework.data.repository.CrudRepository; -import org.springframework.transaction.annotation.Transactional; - -import java.io.Serializable; -import java.util.List; - -@Transactional(value = "transactionManager") -public abstract class AbstractSpringDataJpaService implements IOperations { - - @Override - public T findOne(final long id) { - return getDao().findById(id).orElse(null); - } - - @Override - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public T create(final T entity) { - return getDao().save(entity); - } - - @Override - public T update(final T entity) { - return getDao().save(entity); - } - - @Override - public void delete(final T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(final long entityId) { - getDao().deleteById(entityId); - } - - protected abstract CrudRepository getDao(); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java deleted file mode 100644 index 80568f2fd4..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/BarSpringDataJpaService.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.baeldung.boot.daos.IBarCrudRepository; -import com.baeldung.boot.domain.Bar; -import com.baeldung.boot.services.IBarService; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.repository.CrudRepository; - -import java.io.Serializable; - -public class BarSpringDataJpaService extends AbstractSpringDataJpaService implements IBarService { - - @Autowired - private IBarCrudRepository dao; - - public BarSpringDataJpaService() { - super(); - } - - @Override - protected CrudRepository getDao() { - return dao; - } - - @Override - public Page findPaginated(int page, int size) { - throw new UnsupportedOperationException("Not implemented yet"); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java deleted file mode 100644 index 04eec63854..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/boot/services/impl/FooService.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.boot.services.impl; - -import com.google.common.collect.Lists; -import com.baeldung.boot.daos.IFooDao; -import com.baeldung.boot.domain.Foo; -import com.baeldung.boot.services.IFooService; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@Transactional -public class FooService extends AbstractService implements IFooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - @Override - protected PagingAndSortingRepository getDao() { - return dao; - } - - // custom methods - - @Override - public Foo retrieveByName(final String name) { - return dao.retrieveByName(name); - } - - // overridden to be secured - - @Override - @Transactional(readOnly = true) - public List findAll() { - return Lists.newArrayList(getDao().findAll()); - } - - @Override - public Page findPaginated(Pageable pageable) { - return dao.findAll(pageable); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java deleted file mode 100644 index 3b9aa2cc18..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/MultipleDbApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.multipledb; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MultipleDbApplication { - - public static void main(String[] args) { - SpringApplication.run(MultipleDbApplication.class, args); - } - -} - diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java deleted file mode 100644 index a6f8f0829f..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductAutoConfiguration.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baeldung.multipledb; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * By default, the persistence-multiple-db.properties file is read for - * non auto configuration in PersistenceProductConfiguration. - *

- * If we need to use persistence-multiple-db-boot.properties and auto configuration - * then uncomment the below @Configuration class and comment out PersistenceProductConfiguration. - */ -//@Configuration -@PropertySource({"classpath:persistence-multiple-db-boot.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -@Profile("!tc") -public class PersistenceProductAutoConfiguration { - @Autowired - private Environment env; - - public PersistenceProductAutoConfiguration() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.product"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - @ConfigurationProperties(prefix="spring.second-datasource") - public DataSource productDataSource() { - return DataSourceBuilder.create().build(); - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java deleted file mode 100644 index bcf2cd84eb..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceProductConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.baeldung.multipledb; - -import com.google.common.base.Preconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.util.HashMap; - -@Configuration -@PropertySource({"classpath:persistence-multiple-db.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.product", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") -@Profile("!tc") -public class PersistenceProductConfiguration { - @Autowired - private Environment env; - - public PersistenceProductConfiguration() { - super(); - } - - // - - @Bean - public LocalContainerEntityManagerFactoryBean productEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(productDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.product"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - public DataSource productDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager productTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(productEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java deleted file mode 100644 index e04a1621b2..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserAutoConfiguration.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.multipledb; - -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * By default, the persistence-multiple-db.properties file is read for - * non auto configuration in PersistenceUserConfiguration. - *

- * If we need to use persistence-multiple-db-boot.properties and auto configuration - * then uncomment the below @Configuration class and comment out PersistenceUserConfiguration. - */ -//@Configuration -@PropertySource({"classpath:persistence-multiple-db-boot.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -@Profile("!tc") -public class PersistenceUserAutoConfiguration { - @Autowired - private Environment env; - - public PersistenceUserAutoConfiguration() { - super(); - } - - // - - @Primary - @Bean - public LocalContainerEntityManagerFactoryBean userEntityManager() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(userDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.user"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Bean - @Primary - @ConfigurationProperties(prefix="spring.datasource") - public DataSource userDataSource() { - return DataSourceBuilder.create().build(); - } - - @Primary - @Bean - public PlatformTransactionManager userTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(userEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java deleted file mode 100644 index 6b48455c0c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/PersistenceUserConfiguration.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.multipledb; - -import com.google.common.base.Preconditions; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.*; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; - -import javax.sql.DataSource; -import java.util.HashMap; - -@Configuration -@PropertySource({"classpath:persistence-multiple-db.properties"}) -@EnableJpaRepositories(basePackages = "com.baeldung.multipledb.dao.user", entityManagerFactoryRef = "userEntityManager", transactionManagerRef = "userTransactionManager") -@Profile("!tc") -public class PersistenceUserConfiguration { - @Autowired - private Environment env; - - public PersistenceUserConfiguration() { - super(); - } - - // - - @Primary - @Bean - public LocalContainerEntityManagerFactoryBean userEntityManager() { - System.out.println("loading config"); - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(userDataSource()); - em.setPackagesToScan("com.baeldung.multipledb.model.user"); - - final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - final HashMap properties = new HashMap(); - properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); - properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); - em.setJpaPropertyMap(properties); - - return em; - } - - @Primary - @Bean - public DataSource userDataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("user.jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Primary - @Bean - public PlatformTransactionManager userTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(userEntityManager().getObject()); - return transactionManager; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java deleted file mode 100755 index f1256e2c72..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/product/ProductRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.multipledb.dao.product; - -import java.util.List; - -import org.springframework.data.domain.Pageable; -import org.springframework.data.repository.PagingAndSortingRepository; - -import com.baeldung.multipledb.model.product.Product; - -public interface ProductRepository extends PagingAndSortingRepository { - - - List findAllByPrice(double price, Pageable pageable); -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java deleted file mode 100644 index ae37fde20d..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/PossessionRepository.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.baeldung.multipledb.dao.user; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.multipledb.model.user.PossessionMultipleDB; - -public interface PossessionRepository extends JpaRepository { - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java deleted file mode 100644 index 267a61a93f..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/dao/user/UserRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.baeldung.multipledb.dao.user; - -import org.springframework.data.jpa.repository.JpaRepository; - -import com.baeldung.multipledb.model.user.UserMultipleDB; - -public interface UserRepository extends JpaRepository { -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java deleted file mode 100755 index eaf471043c..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/product/Product.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.multipledb.model.product; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(schema = "products") -public class Product { - - @Id - private int id; - - private String name; - - private double price; - - public Product() { - super(); - } - - private Product(int id, String name, double price) { - super(); - this.id = id; - this.name = name; - this.price = price; - } - - public static Product from(int id, String name, double price) { - return new Product(id, name, price); - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public double getPrice() { - return price; - } - - public void setPrice(final double price) { - this.price = price; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Product [name=") - .append(name) - .append(", id=") - .append(id) - .append("]"); - return builder.toString(); - } -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java deleted file mode 100644 index a6a3c88bd0..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/PossessionMultipleDB.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.multipledb.model.user; - -import javax.persistence.*; - -@Entity -@Table -public class PossessionMultipleDB { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - private String name; - - public PossessionMultipleDB() { - super(); - } - - public PossessionMultipleDB(final String name) { - super(); - - this.name = name; - } - - public long getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + (int) (id ^ (id >>> 32)); - result = (prime * result) + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final PossessionMultipleDB other = (PossessionMultipleDB) obj; - if (id != other.id) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); - return builder.toString(); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java b/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java deleted file mode 100644 index c7cd07f7a1..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/java/com/baeldung/multipledb/model/user/UserMultipleDB.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.baeldung.multipledb.model.user; - -import javax.persistence.*; - -import java.util.List; - -@Entity -@Table(name = "users") -public class UserMultipleDB { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String name; - private int age; - @Column(unique = true, nullable = false) - private String email; - private Integer status; - - @OneToMany - List possessionList; - - public UserMultipleDB() { - super(); - } - - public UserMultipleDB(String name, String email, Integer status) { - this.name = name; - this.email = email; - this.status = status; - } - - public int getId() { - return id; - } - - public void setId(final int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(final String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(final String email) { - this.email = email; - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public int getAge() { - return age; - } - - public void setAge(final int age) { - this.age = age; - } - - public List getPossessionList() { - return possessionList; - } - - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("User [name=").append(name).append(", id=").append(id).append("]"); - return builder.toString(); - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/application.properties b/persistence-modules/spring-data-jpa/src/main/resources/application.properties deleted file mode 100644 index f127dd5e50..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.main.allow-bean-definition-overriding=true - -spring.jpa.properties.hibernate.jdbc.batch_size=4 -spring.jpa.properties.hibernate.order_inserts=true -spring.jpa.properties.hibernate.order_updates=true -spring.jpa.properties.hibernate.generate_statistics=true diff --git a/persistence-modules/spring-data-jpa/src/main/resources/ddd.properties b/persistence-modules/spring-data-jpa/src/main/resources/ddd.properties deleted file mode 100644 index e5126b694b..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/ddd.properties +++ /dev/null @@ -1 +0,0 @@ -spring.datasource.initialization-mode=never \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql b/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql deleted file mode 100644 index deb9d07f05..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/import_entities.sql +++ /dev/null @@ -1,21 +0,0 @@ -insert into Article(id, publication_date, publication_time, creation_date_time) values(1, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:00', 'HH24:MI'), TO_DATE('31/12/2017 07:30', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(2, TO_DATE('01/01/2018', 'DD/MM/YYYY'), TO_DATE('15:30', 'HH24:MI'), TO_DATE('15/12/2017 08:00', 'DD/MM/YYYY HH24:MI')); -insert into Article(id, publication_date, publication_time, creation_date_time) values(3, TO_DATE('15/12/2017', 'DD/MM/YYYY'), TO_DATE('16:00', 'HH24:MI'), TO_DATE('01/12/2017 13:45', 'DD/MM/YYYY HH24:MI')); - -insert into location (id, country, city) values (1, 'Country X', 'City One'); -insert into location (id, country, city) values (2, 'Country X', 'City Two'); -insert into location (id, country, city) values (3, 'Country X', 'City Three'); - -insert into store (id, name, location_id, items_sold, active) values (1, 'Store One', 3, 130000, true); -insert into store (id, name, location_id, items_sold, active) values (2, 'Store Two', 1, 170000, false); - -insert into item_type (id, name) values (1, 'Food'); -insert into item_type (id, name) values (2, 'Furniture'); -insert into item_type (id, name) values (3, 'Electronics'); - -insert into item (id, name, store_id, item_type_id, price, grade, color) values (1, 'Food Item One', 1, 1, 100, 'A', 'Color x'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (2, 'Furniture Item One', 1, 2, 2500, 'B', 'Color y'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (3, 'Food Item Two', 1, 1, 35, 'A', 'Color z'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (5, 'Furniture Item Two', 2, 2, 1600, 'A', 'Color w'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (6, 'Food Item Three', 2, 1, 5, 'B', 'Color a'); -insert into item (id, name, store_id, item_type_id, price, grade, color) values (7, 'Electronics Item One', 2, 3, 999, 'B', 'Color b'); diff --git a/persistence-modules/spring-data-jpa/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties b/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties deleted file mode 100644 index ffca79b3f5..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db-boot.properties +++ /dev/null @@ -1,11 +0,0 @@ -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false - -spring.datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -spring.datasource.username=sa -spring.datasource.password=sa - -spring.second-datasource.jdbcUrl=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS -spring.second-datasource.username=sa -spring.second-datasource.password=sa diff --git a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties b/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties deleted file mode 100644 index 75534e8a54..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/persistence-multiple-db.properties +++ /dev/null @@ -1,13 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -user.jdbc.url=jdbc:h2:mem:spring_jpa_user;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS -jdbc.user=sa -jdbc.pass=sa - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=false -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=false -hibernate.cache.use_query_cache=false \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa/src/main/resources/persistence.properties deleted file mode 100644 index 6bc83edf34..0000000000 --- a/persistence-modules/spring-data-jpa/src/main/resources/persistence.properties +++ /dev/null @@ -1,14 +0,0 @@ -# jdbc.X -jdbc.driverClassName=org.h2.Driver -jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS USERS -jdbc.user=sa -jdbc.pass=sa - -# hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=true -hibernate.cache.use_query_cache=true -hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory - diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index eaccf4acba..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java deleted file mode 100644 index f3697bf39f..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/SpringJpaContextIntegrationTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.config.PersistenceConfiguration; -import com.baeldung.multipledb.PersistenceProductConfiguration; -import com.baeldung.multipledb.PersistenceUserConfiguration; - -@RunWith(SpringRunner.class) -@DataJpaTest(excludeAutoConfiguration = { - PersistenceConfiguration.class, - PersistenceUserConfiguration.class, - PersistenceProductConfiguration.class }) -@ContextConfiguration(classes = Application.class) -public class SpringJpaContextIntegrationTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java deleted file mode 100644 index 20fc3cbeaf..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.baeldung.boot.daos; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.text.SimpleDateFormat; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.domain.Article; - -@RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") -public class ArticleRepositoryIntegrationTest { - - @Autowired - private ArticleRepository repository; - - @Test - public void givenImportedArticlesWhenFindAllByPublicationDateThenArticles1And2Returned() - throws Exception { - List

result = repository.findAllByPublicationDate( - new SimpleDateFormat("yyyy-MM-dd").parse("2018-01-01") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(1, 2).contains(id)) - ); - } - - @Test - public void givenImportedArticlesWhenFindAllByPublicationTimeBetweenThenArticles2And3Returned() - throws Exception { - List
result = repository.findAllByPublicationTimeBetween( - new SimpleDateFormat("HH:mm").parse("15:15"), - new SimpleDateFormat("HH:mm").parse("16:30") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(2, 3).contains(id)) - ); - } - - @Test - public void givenImportedArticlesWhenFindAllWithCreationDateTimeBeforeThenArticles2And3Returned() throws Exception { - List
result = repository.findAllWithCreationDateTimeBefore( - new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-12-15 10:00") - ); - - assertEquals(2, result.size()); - assertTrue(result.stream() - .map(Article::getId) - .allMatch(id -> Arrays.asList(2, 3).contains(id)) - ); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java deleted file mode 100644 index 71f92c94ab..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.boot.daos; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.List; - -import javax.annotation.Resource; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Student; - -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = {Application.class}) -@DirtiesContext -public class ExtendedStudentRepositoryIntegrationTest { - @Resource - private ExtendedStudentRepository extendedStudentRepository; - - @Before - public void setup() { - Student student = new Student(1, "john"); - extendedStudentRepository.save(student); - Student student2 = new Student(2, "johnson"); - extendedStudentRepository.save(student2); - Student student3 = new Student(3, "tom"); - extendedStudentRepository.save(student3); - } - - @Test - public void givenStudents_whenFindByName_thenGetOk() { - List students = extendedStudentRepository.findByAttributeContainsText("name", "john"); - assertThat(students.size()).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java deleted file mode 100644 index 5d73e261a4..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.baeldung.boot.daos; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import java.math.BigDecimal; - -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 com.baeldung.boot.Application; -import com.baeldung.boot.domain.MerchandiseEntity; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -public class InventoryRepositoryIntegrationTest { - - private static final String ORIGINAL_TITLE = "Pair of Pants"; - private static final String UPDATED_TITLE = "Branded Luxury Pants"; - private static final String UPDATED_BRAND = "Armani"; - private static final String ORIGINAL_SHORTS_TITLE = "Pair of Shorts"; - - @Autowired - private InventoryRepository repository; - - @Test - public void shouldCreateNewEntryInDB() { - MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); - pants = repository.save(pants); - - MerchandiseEntity shorts = new MerchandiseEntity(ORIGINAL_SHORTS_TITLE, new BigDecimal(3)); - shorts = repository.save(shorts); - - assertNotNull(pants.getId()); - assertNotNull(shorts.getId()); - assertNotEquals(pants.getId(), shorts.getId()); - } - - @Test - public void shouldUpdateExistingEntryInDB() { - MerchandiseEntity pants = new MerchandiseEntity(ORIGINAL_TITLE, BigDecimal.ONE); - pants = repository.save(pants); - - Long originalId = pants.getId(); - - pants.setTitle(UPDATED_TITLE); - pants.setPrice(BigDecimal.TEN); - pants.setBrand(UPDATED_BRAND); - - MerchandiseEntity result = repository.save(pants); - - assertEquals(originalId, result.getId()); - assertEquals(UPDATED_TITLE, result.getTitle()); - assertEquals(BigDecimal.TEN, result.getPrice()); - assertEquals(UPDATED_BRAND, result.getBrand()); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java deleted file mode 100644 index 9e4b78dce3..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/JpaRepositoriesIntegrationTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.baeldung.boot.daos; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertNotNull; -import static junit.framework.TestCase.assertNull; -import static junit.framework.TestCase.assertTrue; - -import java.util.List; -import java.util.Optional; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.domain.Item; -import com.baeldung.boot.domain.ItemType; -import com.baeldung.boot.domain.Location; -import com.baeldung.boot.domain.Store; - -@RunWith(SpringRunner.class) -@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") -public class JpaRepositoriesIntegrationTest { - @Autowired - private LocationRepository locationRepository; - @Autowired - private StoreRepository storeRepository; - @Autowired - private ItemTypeRepository compositeRepository; - @Autowired - private ReadOnlyLocationRepository readOnlyRepository; - - @Test - public void whenSaveLocation_ThenGetSameLocation() { - Location location = new Location(); - location.setId(100L); - location.setCountry("Country H"); - location.setCity("City Hundred"); - location = locationRepository.saveAndFlush(location); - - Location otherLocation = locationRepository.getOne(location.getId()); - assertEquals("Country H", otherLocation.getCountry()); - assertEquals("City Hundred", otherLocation.getCity()); - - locationRepository.delete(otherLocation); - } - - @Test - public void givenLocationId_whenFindStores_thenGetStores() { - List stores = storeRepository.findStoreByLocationId(1L); - assertEquals(1, stores.size()); - } - - @Test - public void givenItemTypeId_whenDeleted_ThenItemTypeDeleted() { - Optional itemType = compositeRepository.findById(1L); - assertTrue(itemType.isPresent()); - compositeRepository.deleteCustom(itemType.get()); - itemType = compositeRepository.findById(1L); - assertFalse(itemType.isPresent()); - } - - @Test - public void givenItemId_whenUsingCustomRepo_ThenDeleteAppropriateEntity() { - Item item = compositeRepository.findItemById(1L); - assertNotNull(item); - compositeRepository.deleteCustom(item); - item = compositeRepository.findItemById(1L); - assertNull(item); - } - - @Test - public void givenItemAndItemType_WhenAmbiguousDeleteCalled_ThenItemTypeDeletedAndNotItem() { - Optional itemType = compositeRepository.findById(1L); - assertTrue(itemType.isPresent()); - Item item = compositeRepository.findItemById(2L); - assertNotNull(item); - - compositeRepository.findThenDelete(1L); - Optional sameItemType = compositeRepository.findById(1L); - assertFalse(sameItemType.isPresent()); - Item sameItem = compositeRepository.findItemById(2L); - assertNotNull(sameItem); - } - - @Test - public void whenCreatingReadOnlyRepo_thenHaveOnlyReadOnlyOperationsAvailable() { - Optional location = readOnlyRepository.findById(1L); - assertNotNull(location); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java deleted file mode 100644 index b2581b8034..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryCommon.java +++ /dev/null @@ -1,545 +0,0 @@ -package com.baeldung.boot.daos; - -import org.junit.After; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; -import org.springframework.data.jpa.domain.JpaSort; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.boot.daos.user.UserRepository; -import com.baeldung.boot.domain.User; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import java.time.LocalDate; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; - -public class UserRepositoryCommon { - - final String USER_EMAIL = "email@example.com"; - final String USER_EMAIL2 = "email2@example.com"; - final String USER_EMAIL3 = "email3@example.com"; - final String USER_EMAIL4 = "email4@example.com"; - final Integer INACTIVE_STATUS = 0; - final Integer ACTIVE_STATUS = 1; - final String USER_EMAIL5 = "email5@example.com"; - final String USER_EMAIL6 = "email6@example.com"; - final String USER_NAME_ADAM = "Adam"; - final String USER_NAME_PETER = "Peter"; - - @Autowired - protected UserRepository userRepository; - @Autowired - private EntityManager entityManager; - - @Test - @Transactional - public void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - User user4 = new User(); - user4.setName("SAMPLE"); - user4.setEmail(USER_EMAIL4); - userRepository.save(user4); - - try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { - assertThat(foundUsersStream.count()).isEqualTo(3l); - } - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotation_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsers(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindAllWithQueryAnnotationNative_ThenReturnCollectionWithActiveUsers() { - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - user1.setStatus(ACTIVE_STATUS); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_ADAM); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User user3 = new User(); - user3.setName(USER_NAME_ADAM); - user3.setEmail(USER_EMAIL3); - user3.setStatus(INACTIVE_STATUS); - userRepository.save(user3); - - Collection allActiveUsers = userRepository.findAllActiveUsersNative(); - - assertThat(allActiveUsers.size()).isEqualTo(2); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotation_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatus(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUserInDB_WhenFindUserByStatusWithQueryAnnotationNative_ThenReturnActiveUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByStatusNative(ACTIVE_STATUS); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationIndexedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParams(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNativeNamedParams_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByStatusAndNameNamedParamsNative(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByStatusAndNameWithQueryAnnotationNamedParamsCustomNames_ThenReturnOneUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - user2.setStatus(ACTIVE_STATUS); - userRepository.save(user2); - - User userByStatus = userRepository.findUserByUserStatusAndUserName(ACTIVE_STATUS, USER_NAME_ADAM); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationIndexedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLike("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNamedParams_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNamedParam("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindUserByNameLikeWithQueryAnnotationNative_ThenReturnUser() { - User user = new User(); - user.setName(USER_NAME_ADAM); - user.setEmail(USER_EMAIL); - user.setStatus(ACTIVE_STATUS); - userRepository.save(user); - - User userByStatus = userRepository.findUserByNameLikeNative("Ad"); - - assertThat(userByStatus.getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - assertThat(usersSortByName.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test(expected = PropertyReferenceException.class) - public void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - - List usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllSortWithFunctionQueryAnnotationJPQL_ThenReturnUsersSorted() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - - userRepository.findAllUsers(Sort.by("name")); - - List usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - - assertThat(usersSortByNameLength.get(0) - .getName()).isEqualTo(USER_NAME_ADAM); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationJPQL_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3)); - - assertThat(usersPage.getContent() - .get(0) - .getName()).isEqualTo("SAMPLE1"); - } - - @Test - public void givenUsersInDB_WhenFindAllWithPageRequestQueryAnnotationNative_ThenReturnPageOfUsers() { - userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL4, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS)); - - Page usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3)); - - assertThat(usersSortByNameLength.getContent() - .get(0) - .getName()).isEqualTo(USER_NAME_PETER); - } - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationJPQL_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - - int updatedUsersSize = userRepository.updateUserSetStatusForName(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - @Test - public void givenUsersInDB_WhenFindByEmailsWithDynamicQuery_ThenReturnCollection() { - - User user1 = new User(); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - User user3 = new User(); - user3.setEmail(USER_EMAIL3); - userRepository.save(user3); - - Set emails = new HashSet<>(); - emails.add(USER_EMAIL2); - emails.add(USER_EMAIL3); - - Collection usersWithEmails = userRepository.findUserByEmails(emails); - - assertThat(usersWithEmails.size()).isEqualTo(2); - } - - @Test - public void givenUsersInDBWhenFindByNameListReturnCollection() { - - User user1 = new User(); - user1.setName(USER_NAME_ADAM); - user1.setEmail(USER_EMAIL); - userRepository.save(user1); - - User user2 = new User(); - user2.setName(USER_NAME_PETER); - user2.setEmail(USER_EMAIL2); - userRepository.save(user2); - - List names = Arrays.asList(USER_NAME_ADAM, USER_NAME_PETER); - - List usersWithNames = userRepository.findUserByNameList(names); - - assertThat(usersWithNames.size()).isEqualTo(2); - } - - - @Test - @Transactional - public void whenInsertedWithQuery_ThenUserIsPersisted() { - userRepository.insertUser(USER_NAME_ADAM, 1, USER_EMAIL, ACTIVE_STATUS, true); - userRepository.insertUser(USER_NAME_PETER, 1, USER_EMAIL2, ACTIVE_STATUS, true); - - User userAdam = userRepository.findUserByNameLike(USER_NAME_ADAM); - User userPeter = userRepository.findUserByNameLike(USER_NAME_PETER); - - assertThat(userAdam).isNotNull(); - assertThat(userAdam.getEmail()).isEqualTo(USER_EMAIL); - assertThat(userPeter).isNotNull(); - assertThat(userPeter.getEmail()).isEqualTo(USER_EMAIL2); - } - - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr01")) { - assertTrue(users.allMatch(usr -> usr.equals(usr01))); - } - } - - @Test - @Transactional - public void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - try (Stream users = userRepository.findAllByName("usr00")) { - assertEquals(0, users.count()); - } - } - - @Test - public void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { - User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List users = userRepository.findUsersWithGmailAddress(); - assertEquals(1, users.size()); - assertEquals(usr02, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); - - List users = userRepository.findAll(); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - public void givenTwoUsers_whenFindAllUsersByPredicates_ThenUserUsr01() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - - userRepository.save(usr01); - userRepository.save(usr02); - - List> predicates = new ArrayList<>(); - predicates.add(usr -> usr.getCreationDate().isAfter(LocalDate.of(2017, 12, 31))); - predicates.add(usr -> usr.getEmail().endsWith(".com")); - - List users = userRepository.findAllUsersByPredicates(predicates); - - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeactivateUsersNotLoggedInSince_ThenUserUsr02Deactivated() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.deactivateUsersNotLoggedInSince(LocalDate.of(2018, 8, 1)); - - List users = userRepository.findAllUsers(Sort.by(Sort.Order.asc("name"))); - assertTrue(users.get(0).isActive()); - assertFalse(users.get(1).isActive()); - } - - @Test - @Transactional - public void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - int deletedUsersCount = userRepository.deleteDeactivatedUsers(); - - List users = userRepository.findAll(); - assertEquals(1, users.size()); - assertEquals(usr01, users.get(0)); - assertEquals(1, deletedUsersCount); - } - - @Test - @Transactional - public void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { - User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); - usr01.setLastLoginDate(LocalDate.now()); - User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); - usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); - usr02.setActive(false); - - userRepository.save(usr01); - userRepository.save(usr02); - - userRepository.addDeletedColumn(); - - Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); - assertEquals(0, nativeQuery.getResultList().get(0)); - } - - @After - public void cleanUp() { - userRepository.deleteAll(); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java deleted file mode 100644 index 1b1d264574..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@DirtiesContext -public class UserRepositoryIntegrationTest extends UserRepositoryCommon { - - @Test - @Transactional - public void givenUsersInDBWhenUpdateStatusForNameModifyingQueryAnnotationNativeThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNative(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java deleted file mode 100644 index 99eabc8271..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCAutoLiveTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import com.baeldung.util.BaeldungPostgresqlContainer; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Created by adam. - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles({"tc", "tc-auto"}) -public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance(); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNativePostgres_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java deleted file mode 100644 index be8843c166..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/daos/UserRepositoryTCLiveTest.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.baeldung.boot.daos; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.User; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.util.TestPropertyValues; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.Transactional; -import org.testcontainers.containers.PostgreSQLContainer; - -import java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -@ActiveProfiles("tc") -@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class}) -public class UserRepositoryTCLiveTest extends UserRepositoryCommon { - - @ClassRule - public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1") - .withDatabaseName("integration-tests-db") - .withUsername("sa") - .withPassword("sa"); - - @Test - @Transactional - public void givenUsersInDB_WhenUpdateStatusForNameModifyingQueryAnnotationNative_ThenModifyMatchingUsers() { - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE1", LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, ACTIVE_STATUS)); - userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL4, ACTIVE_STATUS)); - userRepository.flush(); - - int updatedUsersSize = userRepository.updateUserSetStatusForNameNativePostgres(INACTIVE_STATUS, "SAMPLE"); - - assertThat(updatedUsersSize).isEqualTo(2); - } - - static class Initializer - implements ApplicationContextInitializer { - public void initialize(ConfigurableApplicationContext configurableApplicationContext) { - TestPropertyValues.of( - "spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(), - "spring.datasource.username=" + postgreSQLContainer.getUsername(), - "spring.datasource.password=" + postgreSQLContainer.getPassword() - ).applyTo(configurableApplicationContext.getEnvironment()); - } - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java deleted file mode 100644 index e76b932cb9..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate2EventsIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import com.baeldung.boot.ddd.event.Aggregate2; -import com.baeldung.boot.ddd.event.Aggregate2Repository; -import com.baeldung.boot.ddd.event.DomainEvent; - -@SpringJUnitConfig -@SpringBootTest -class Aggregate2EventsIntegrationTest { - @MockBean - private TestEventHandler eventHandler; - @Autowired - private Aggregate2Repository repository; - - // @formatter:off - @DisplayName("given aggregate with @AfterDomainEventPublication," - + " when do domain operation and save twice," - + " then an event is published only for the first time") - // @formatter:on - @Test - void afterDomainEvents() { - // given - Aggregate2 aggregate = new Aggregate2(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - - @BeforeEach - void beforeEach() { - repository.deleteAll(); - } - - // @formatter:off - @DisplayName("given aggregate with @DomainEvents," - + " when do domain operation and save," - + " then an event is published") - // @formatter:on - @Test - void domainEvents() { - // given - Aggregate2 aggregate = new Aggregate2(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java deleted file mode 100644 index 4193e932ee..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/Aggregate3EventsIntegrationTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import com.baeldung.boot.ddd.event.Aggregate3; -import com.baeldung.boot.ddd.event.Aggregate3Repository; -import com.baeldung.boot.ddd.event.DomainEvent; - -@SpringJUnitConfig -@SpringBootTest -class Aggregate3EventsIntegrationTest { - - @MockBean - private TestEventHandler eventHandler; - @Autowired - private Aggregate3Repository repository; - - // @formatter:off - @DisplayName("given aggregate extending AbstractAggregateRoot," - + " when do domain operation and save twice," - + " then an event is published only for the first time") - // @formatter:on - @Test - void afterDomainEvents() { - // given - Aggregate3 aggregate = new Aggregate3(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - - // @formatter:off - @DisplayName("given aggregate extending AbstractAggregateRoot," - + " when do domain operation and save," - + " then an event is published") - // @formatter:on - @Test - void domainEvents() { - // given - Aggregate3 aggregate = new Aggregate3(); - - // when - aggregate.domainOperation(); - repository.save(aggregate); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java deleted file mode 100644 index ac607063b2..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/AggregateEventsIntegrationTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.boot.ddd.event; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.annotation.Bean; -import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; - -import com.baeldung.boot.ddd.event.Aggregate; -import com.baeldung.boot.ddd.event.AggregateRepository; -import com.baeldung.boot.ddd.event.DomainEvent; -import com.baeldung.boot.ddd.event.DomainService; - -@SpringJUnitConfig -@SpringBootTest -class AggregateEventsIntegrationTest { - - @Autowired - private DomainService domainService; - - @MockBean - private TestEventHandler eventHandler; - @Autowired - private ApplicationEventPublisher eventPublisher; - @Autowired - private AggregateRepository repository; - - // @formatter:off - @DisplayName("given existing aggregate," - + " when do domain operation directly on aggregate," - + " then domain event is NOT published") - // @formatter:on - @Test - void aggregateEventsTest() { - Aggregate existingDomainEntity = new Aggregate(0, eventPublisher); - repository.save(existingDomainEntity); - - // when - repository.findById(existingDomainEntity.getId()) - .get() - .domainOperation(); - - // then - verifyZeroInteractions(eventHandler); - } - - @BeforeEach - void beforeEach() { - repository.deleteAll(); - } - - // @formatter:off - @DisplayName("given existing aggregate," - + " when do domain operation on service," - + " then domain event is published") - // @formatter:on - @Test - void serviceEventsTest() { - Aggregate existingDomainEntity = new Aggregate(1, eventPublisher); - repository.save(existingDomainEntity); - - // when - domainService.serviceDomainOperation(existingDomainEntity.getId()); - - // then - verify(eventHandler, times(1)).handleEvent(any(DomainEvent.class)); - } - - @TestConfiguration - public static class TestConfig { - @Bean - public DomainService domainService(AggregateRepository repository, ApplicationEventPublisher eventPublisher) { - return new DomainService(repository, eventPublisher); - } - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java deleted file mode 100644 index 0f499834eb..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/ddd/event/TestEventHandler.java +++ /dev/null @@ -1,14 +0,0 @@ -/** - * - */ -package com.baeldung.boot.ddd.event; - -import org.springframework.transaction.event.TransactionalEventListener; - -import com.baeldung.boot.ddd.event.DomainEvent; - -interface TestEventHandler { - @TransactionalEventListener - void handleEvent(DomainEvent event); - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java deleted file mode 100644 index bf0c85fca6..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/AbstractServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,252 +0,0 @@ -package com.baeldung.boot.services; - -import com.baeldung.boot.domain.Foo; -import com.baeldung.boot.services.IOperations; -import com.baeldung.util.IDUtil; -import org.hamcrest.Matchers; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.dao.DataAccessException; - -import java.io.Serializable; -import java.util.List; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.*; - -public abstract class AbstractServicePersistenceIntegrationTest { - - // tests - - // find - one - - @Test - /**/public final void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoResourceIsReceived() { - // When - final Foo createdResource = getApi().findOne(IDUtil.randomPositiveLong()); - - // Then - assertNull(createdResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenNoExceptions() { - final Foo existingResource = persistNewEntity(); - getApi().findOne(existingResource.getId()); - } - - @Test - public void givenResourceDoesNotExist_whenResourceIsRetrieved_thenNoExceptions() { - getApi().findOne(IDUtil.randomPositiveLong()); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenTheResultIsNotNull() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertNotNull(retrievedResource); - } - - @Test - public void givenResourceExists_whenResourceIsRetrieved_thenResourceIsRetrievedCorrectly() { - final Foo existingResource = persistNewEntity(); - final Foo retrievedResource = getApi().findOne(existingResource.getId()); - assertEquals(existingResource, retrievedResource); - } - - // find - one - by name - - // find - all - - @Test - /**/public void whenAllResourcesAreRetrieved_thenNoExceptions() { - getApi().findAll(); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenTheResultIsNotNull() { - final List resources = getApi().findAll(); - - assertNotNull(resources); - } - - @Test - /**/public void givenAtLeastOneResourceExists_whenAllResourcesAreRetrieved_thenRetrievedResourcesAreNotEmpty() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - assertThat(allResources, not(Matchers. empty())); - } - - @Test - /**/public void givenAnResourceExists_whenAllResourcesAreRetrieved_thenTheExistingResourceIsIndeedAmongThem() { - final Foo existingResource = persistNewEntity(); - - final List resources = getApi().findAll(); - - assertThat(resources, hasItem(existingResource)); - } - - @Test - /**/public void whenAllResourcesAreRetrieved_thenResourcesHaveIds() { - persistNewEntity(); - - // When - final List allResources = getApi().findAll(); - - // Then - for (final Foo resource : allResources) { - assertNotNull(resource.getId()); - } - } - - // create - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsCreated_thenException() { - getApi().create(null); - } - - @Test - /**/public void whenResourceIsCreated_thenNoExceptions() { - persistNewEntity(); - } - - @Test - /**/public void whenResourceIsCreated_thenResourceIsRetrievable() { - final Foo existingResource = persistNewEntity(); - - assertNotNull(getApi().findOne(existingResource.getId())); - } - - @Test - /**/public void whenResourceIsCreated_thenSavedResourceIsEqualToOriginalResource() { - final Foo originalResource = createNewEntity(); - final Foo savedResource = getApi().create(originalResource); - - assertEquals(originalResource, savedResource); - } - - @Test(expected = RuntimeException.class) - public void whenResourceWithFailedConstraintsIsCreated_thenException() { - final Foo invalidResource = createNewEntity(); - invalidate(invalidResource); - - getApi().create(invalidResource); - } - - /** - * -- specific to the persistence engine - */ - @Test(expected = DataAccessException.class) - @Ignore("Hibernate simply ignores the id silently and still saved (tracking this)") - public void whenResourceWithIdIsCreated_thenDataAccessException() { - final Foo resourceWithId = createNewEntity(); - resourceWithId.setId(IDUtil.randomPositiveLong()); - - getApi().create(resourceWithId); - } - - // update - - @Test(expected = RuntimeException.class) - /**/public void whenNullResourceIsUpdated_thenException() { - getApi().update(null); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenNoExceptions() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - getApi().update(existingResource); - } - - /** - * - can also be the ConstraintViolationException which now occurs on the update operation will not be translated; as a consequence, it will be a TransactionSystemException - */ - @Test(expected = RuntimeException.class) - public void whenResourceIsUpdatedWithFailedConstraints_thenException() { - final Foo existingResource = persistNewEntity(); - invalidate(existingResource); - - getApi().update(existingResource); - } - - @Test - /**/public void givenResourceExists_whenResourceIsUpdated_thenUpdatesArePersisted() { - // Given - final Foo existingResource = persistNewEntity(); - - // When - change(existingResource); - getApi().update(existingResource); - - final Foo updatedResource = getApi().findOne(existingResource.getId()); - - // Then - assertEquals(existingResource, updatedResource); - } - - // delete - - // @Test(expected = RuntimeException.class) - // public void givenResourceDoesNotExists_whenResourceIsDeleted_thenException() { - // // When - // getApi().delete(IDUtil.randomPositiveLong()); - // } - // - // @Test(expected = RuntimeException.class) - // public void whenResourceIsDeletedByNegativeId_thenException() { - // // When - // getApi().delete(IDUtil.randomNegativeLong()); - // } - // - // @Test - // public void givenResourceExists_whenResourceIsDeleted_thenNoExceptions() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // } - // - // @Test - // /**/public final void givenResourceExists_whenResourceIsDeleted_thenResourceNoLongerExists() { - // // Given - // final Foo existingResource = persistNewEntity(); - // - // // When - // getApi().delete(existingResource.getId()); - // - // // Then - // assertNull(getApi().findOne(existingResource.getId())); - // } - - // template method - - protected Foo createNewEntity() { - return new Foo(randomAlphabetic(6)); - } - - protected abstract IOperations getApi(); - - private final void invalidate(final Foo entity) { - entity.setName(null); - } - - private final void change(final Foo entity) { - entity.setName(randomAlphabetic(6)); - } - - protected Foo persistNewEntity() { - return getApi().create(createNewEntity()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 72de4918a2..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.boot.services; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNotNull; - -import org.junit.Ignore; -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.dao.InvalidDataAccessApiUsageException; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Foo; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -public class FooServicePersistenceIntegrationTest extends AbstractServicePersistenceIntegrationTest { - - @Autowired - private IFooService service; - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @Test - public final void whenEntityIsCreated_thenNoExceptions() { - service.create(new Foo(randomAlphabetic(6))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - // custom Query method - - @Test - public final void givenUsingCustomQuery_whenRetrievingEntity_thenFound() { - final String name = randomAlphabetic(6); - service.create(new Foo(name)); - - final Foo retrievedByName = service.retrieveByName(name); - assertNotNull(retrievedByName); - } - - // work in progress - - @Test(expected = InvalidDataAccessApiUsageException.class) - @Ignore("Right now, persist has saveOrUpdate semantics, so this will no longer fail") - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - // API - - @Override - protected final IOperations getApi() { - return service; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java deleted file mode 100644 index 644d1ec805..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/boot/services/SpringDataJPABarAuditIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.boot.services; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.boot.Application; -import com.baeldung.boot.domain.Bar; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=Application.class) -public class SpringDataJPABarAuditIntegrationTest { - - private static Logger logger = LoggerFactory.getLogger(SpringDataJPABarAuditIntegrationTest.class); - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - logger.info("setUpBeforeClass()"); - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - logger.info("tearDownAfterClass()"); - } - - @Autowired - @Qualifier("barSpringDataJpaService") - private IBarService barService; - - @Autowired - private EntityManagerFactory entityManagerFactory; - - private EntityManager em; - - @Before - public void setUp() throws Exception { - logger.info("setUp()"); - em = entityManagerFactory.createEntityManager(); - } - - @After - public void tearDown() throws Exception { - logger.info("tearDown()"); - em.close(); - } - - @Test - @WithMockUser(username = "tutorialuser") - public final void whenBarsModified_thenBarsAudited() { - Bar bar = new Bar("BAR1"); - barService.create(bar); - assertEquals(bar.getCreatedDate(), bar.getModifiedDate()); - assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); - bar.setName("BAR2"); - bar = barService.update(bar); - assertTrue(bar.getCreatedDate() < bar.getModifiedDate()); - assertEquals("tutorialuser", bar.getCreatedBy(), bar.getModifiedBy()); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java deleted file mode 100644 index a1f4a3fa2c..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/JpaMultipleDBIntegrationTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.multipledb; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.Collections; -import java.util.Optional; - -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; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.dao.user.PossessionRepository; -import com.baeldung.multipledb.dao.user.UserRepository; -import com.baeldung.multipledb.model.product.Product; -import com.baeldung.multipledb.model.user.PossessionMultipleDB; -import com.baeldung.multipledb.model.user.UserMultipleDB; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) -@EnableTransactionManagement -public class JpaMultipleDBIntegrationTest { - - @Autowired - private UserRepository userRepository; - - @Autowired - private PossessionRepository possessionRepository; - - @Autowired - private ProductRepository productRepository; - - // tests - - @Test - @Transactional("userTransactionManager") - public void whenCreatingUser_thenCreated() { - UserMultipleDB user = new UserMultipleDB(); - user.setName("John"); - user.setEmail("john@test.com"); - user.setAge(20); - PossessionMultipleDB p = new PossessionMultipleDB("sample"); - p = possessionRepository.save(p); - user.setPossessionList(Collections.singletonList(p)); - user = userRepository.save(user); - final Optional result = userRepository.findById(user.getId()); - assertTrue(result.isPresent()); - System.out.println(result.get().getPossessionList()); - assertEquals(1, result.get().getPossessionList().size()); - } - - @Test - @Transactional("userTransactionManager") - public void whenCreatingUsersWithSameEmail_thenRollback() { - UserMultipleDB user1 = new UserMultipleDB(); - user1.setName("John"); - user1.setEmail("john@test.com"); - user1.setAge(20); - user1 = userRepository.save(user1); - assertTrue(userRepository.findById(user1.getId()).isPresent()); - - UserMultipleDB user2 = new UserMultipleDB(); - user2.setName("Tom"); - user2.setEmail("john@test.com"); - user2.setAge(10); - try { - user2 = userRepository.save(user2); - userRepository.flush(); - fail("DataIntegrityViolationException should be thrown!"); - } catch (final DataIntegrityViolationException e) { - // Expected - } catch (final Exception e) { - fail("DataIntegrityViolationException should be thrown, instead got: " + e); - } - } - - @Test - @Transactional("productTransactionManager") - public void whenCreatingProduct_thenCreated() { - Product product = new Product(); - product.setName("Book"); - product.setId(2); - product.setPrice(20); - product = productRepository.save(product); - - assertTrue(productRepository.findById(product.getId()).isPresent()); - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java deleted file mode 100644 index 9bfba61a3b..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.baeldung.multipledb; - -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import org.junit.Before; -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.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.multipledb.PersistenceProductConfiguration; -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.Product; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) -@EnableTransactionManagement -public class ProductRepositoryIntegrationTest { - - @Autowired - private ProductRepository productRepository; - - @Before - @Transactional("productTransactionManager") - public void setUp() { - productRepository.save(Product.from(1001, "Book", 21)); - productRepository.save(Product.from(1002, "Coffee", 10)); - productRepository.save(Product.from(1003, "Jeans", 30)); - productRepository.save(Product.from(1004, "Shirt", 32)); - productRepository.save(Product.from(1005, "Bacon", 10)); - } - - @Test - public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1001, 1002) - .contains(id))); - } - - @Test - public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { - Pageable pageRequest = PageRequest.of(1, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1003, 1004) - .contains(id))); - } - - @Test - public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { - Pageable pageRequest = PageRequest.of(2, 2); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(1)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1005) - .contains(id))); - } - - @Test - public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1005, 1001, 1002))); - - } - - @Test - public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") - .descending()); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(3)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001))); - - } - - @Test - public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { - Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") - .descending() - .and(Sort.by("name"))); - - Page result = productRepository.findAll(pageRequest); - - assertThat(result.getContent(), hasSize(5)); - assertThat(result.getContent() - .stream() - .map(Product::getId) - .collect(Collectors.toList()), equalTo(Arrays.asList(1004, 1003, 1001, 1005, 1002))); - - } - - @Test - public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { - Pageable pageRequest = PageRequest.of(0, 2); - - List result = productRepository.findAllByPrice(10, pageRequest); - - assertThat(result, hasSize(2)); - assertTrue(result.stream() - .map(Product::getId) - .allMatch(id -> Arrays.asList(1002, 1005) - .contains(id))); - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java deleted file mode 100644 index e5ad2dd448..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/BaeldungPostgresqlContainer.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.util; - -import org.testcontainers.containers.PostgreSQLContainer; - -public class BaeldungPostgresqlContainer extends PostgreSQLContainer { - - private static final String IMAGE_VERSION = "postgres:11.1"; - - private static BaeldungPostgresqlContainer container; - - - private BaeldungPostgresqlContainer() { - super(IMAGE_VERSION); - } - - public static BaeldungPostgresqlContainer getInstance() { - if (container == null) { - container = new BaeldungPostgresqlContainer(); - } - return container; - } - - @Override - public void start() { - super.start(); - System.setProperty("DB_URL", container.getJdbcUrl()); - System.setProperty("DB_USERNAME", container.getUsername()); - System.setProperty("DB_PASSWORD", container.getPassword()); - } - - @Override - public void stop() { - //do nothing, JVM handles shut down - } -} diff --git a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java b/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java deleted file mode 100644 index 45e72e046d..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/java/com/baeldung/util/IDUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.util; - -import java.util.Random; - -public final class IDUtil { - - private IDUtil() { - throw new AssertionError(); - } - - // API - - public static String randomPositiveLongAsString() { - return Long.toString(randomPositiveLong()); - } - - public static String randomNegativeLongAsString() { - return Long.toString(randomNegativeLong()); - } - - public static long randomPositiveLong() { - long id = new Random().nextLong() * 10000; - id = (id < 0) ? (-1 * id) : id; - return id; - } - - private static long randomNegativeLong() { - long id = new Random().nextLong() * 10000; - id = (id > 0) ? (-1 * id) : id; - return id; - } - -} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties deleted file mode 100644 index c3005d861f..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/resources/application-tc-auto.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for test containers testing -spring.datasource.url=${DB_URL} -spring.datasource.username=${DB_USERNAME} -spring.datasource.password=${DB_PASSWORD} diff --git a/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties b/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties deleted file mode 100644 index 3bf8693d53..0000000000 --- a/persistence-modules/spring-data-jpa/src/test/resources/application-tc.properties +++ /dev/null @@ -1,4 +0,0 @@ -# configuration for Test Containers testing -spring.datasource.driver-class-name=org.postgresql.Driver -spring.jpa.hibernate.ddl-auto=create-drop -spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false From 6298b6b64a97090252b3b6d3a13e8ca42fb60e56 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 19 Jul 2020 14:36:21 +0530 Subject: [PATCH 058/155] JAVA-66: parent module pom changes corresponding to module renaming --- persistence-modules/pom.xml | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index f1154f203b..c598ad8805 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -59,11 +59,12 @@ spring-data-elasticsearch spring-data-gemfire spring-data-geode - spring-data-jpa - spring-data-jpa-2 - spring-data-jpa-3 - spring-data-jpa-4 - spring-data-jpa-5 + spring-data-jpa-annotations + spring-data-jpa-crud + spring-data-jpa-enterprise + spring-data-jpa-filtering + spring-data-jpa-query + spring-data-jpa-repo spring-data-keyvalue spring-data-mongodb spring-data-neo4j From 8309e562681e944970f2f7277d06f33258031cc7 Mon Sep 17 00:00:00 2001 From: developerDiv Date: Sun, 19 Jul 2020 15:44:48 +0100 Subject: [PATCH 059/155] Rename tests --- .../mockito/argumentcaptor/Credentials.java | 1 - .../argumentcaptor/EmailServiceUnitTest.java | 21 +++++++++---------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java index 5aec15505e..d5d60bb6fc 100644 --- a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/Credentials.java @@ -6,7 +6,6 @@ public class Credentials { private final String key; public Credentials(String name, String password, String key) { - this.name = name; this.password = password; this.key = key; diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index cdae118e92..2208bc7c7b 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -32,7 +32,7 @@ public class EmailServiceUnitTest { public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() { String to = "info@baeldung.com"; String subject = "Using ArgumentCaptor"; - String body = "Article on using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; emailService.send(to, subject, body, false); @@ -42,10 +42,10 @@ public class EmailServiceUnitTest { } @Test - public void send_whenDoesSupportHtml_expectHTMLEmailFormat() { - String to = "baeldung@baeldung.com"; - String subject = "Great New Course!"; - String body = "Try out our new course."; + public void whenDoesSupportHtml_expectHTMLEmailFormat() { + String to = "info@baeldung.com"; + String subject = "Using ArgumentCaptor"; + String body = "Hey, let'use ArgumentCaptor"; emailService.send(to, subject, body, true); @@ -55,7 +55,7 @@ public class EmailServiceUnitTest { } @Test - public void getServiceStatus_whenServiceRunning_expectUpResponse() { + public void whenServiceRunning_expectUpResponse() { when(platform.getServiceStatus()).thenReturn("OK"); ServiceStatus serviceStatus = emailService.checkServiceStatus(); @@ -64,7 +64,7 @@ public class EmailServiceUnitTest { } @Test - public void getServiceStatus_whenServiceNotRunning_expectDownResponse() { + public void whenServiceNotRunning_expectDownResponse() { when(platform.getServiceStatus()).thenReturn("Error"); ServiceStatus serviceStatus = emailService.checkServiceStatus(); @@ -73,7 +73,7 @@ public class EmailServiceUnitTest { } @Test - public void usingArgumemtMatcher_whenAuthenticatedWithValidCredentials_expectTrue() { + public void usingArgumentMatcher_whenAuthenticatedWithValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); @@ -90,11 +90,10 @@ public class EmailServiceUnitTest { } @Test - public void authenticate_whenNotAuthenticated_expectFalse() { + public void whenNotAuthenticated_expectFalse() { Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); - when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); + when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); assertFalse(emailService.authenticatedSuccessfully(credentials)); - assertEquals(credentials, credentialsCaptor.getValue()); } } \ No newline at end of file From 6ced667bd548586eb31c25ed8e9decdde536677a Mon Sep 17 00:00:00 2001 From: karan Date: Wed, 15 Jul 2020 00:54:16 -0400 Subject: [PATCH 060/155] pathvariable-annotation correct formatting --- .../CustomWebMvcConfigurationSupport.java | 2 +- .../SiteController.java | 2 +- .../PathVariableAnnotationController.java | 79 +++++++++++++++++++ 3 files changed, 81 insertions(+), 2 deletions(-) rename spring-mvc-java-2/src/main/java/com/baeldung/{pathvariable => pathvariable.dottruncated}/CustomWebMvcConfigurationSupport.java (92%) rename spring-mvc-java-2/src/main/java/com/baeldung/{pathvariable => pathvariable.dottruncated}/SiteController.java (96%) create mode 100644 spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/CustomWebMvcConfigurationSupport.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/CustomWebMvcConfigurationSupport.java similarity index 92% rename from spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/CustomWebMvcConfigurationSupport.java rename to spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/CustomWebMvcConfigurationSupport.java index 12c208c623..24d5a447ab 100644 --- a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/CustomWebMvcConfigurationSupport.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/CustomWebMvcConfigurationSupport.java @@ -1,4 +1,4 @@ -package com.baeldung.pathvariable; +package com.baeldung.pathvariable.dottruncated; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/SiteController.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/SiteController.java similarity index 96% rename from spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/SiteController.java rename to spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/SiteController.java index 493161b0eb..c9584afdc9 100644 --- a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/SiteController.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable.dottruncated/SiteController.java @@ -1,4 +1,4 @@ -package com.baeldung.pathvariable; +package com.baeldung.pathvariable.dottruncated; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java new file mode 100644 index 0000000000..624ba2d105 --- /dev/null +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java @@ -0,0 +1,79 @@ +package com.baeldung.pathvariable; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; +import java.util.Optional; + +@RestController +public class PathVariableAnnotationController { + @GetMapping("/api/employees/{id}") + @ResponseBody + public String getEmployeesById(@PathVariable String id) { + return "ID: " + id; + } + + @GetMapping("/api/employeeswithvariable/{id}") + @ResponseBody + public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) { + return "ID: " + employeeId; + } + + @GetMapping("/api/employees/{id}/{name}") + @ResponseBody + public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) { + return "ID: " + id + ", name: " + name; + } + + @GetMapping("/api/employeeswithmapvariable/{id}/{name}") + @ResponseBody + public String getEmployeesByIdAndNameWithMapVariable(@PathVariable Map pathVarsMap) { + String id = pathVarsMap.get("id"); + String name = pathVarsMap.get("name"); + if (id != null && name != null) { + return "ID: " + id + ", name: " + name; + } else { + return "Missing Parameters"; + } + } + + @GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" }) + @ResponseBody + public String getEmployeesByIdWithRequired(@PathVariable String id) { + return "ID: " + id; + } + + @GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" }) + @ResponseBody + public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) { + if (id != null) { + return "ID: " + id; + } else { + return "ID missing"; + } + } + + @GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" }) + @ResponseBody + public String getEmployeesByIdWithOptional(@PathVariable Optional id) { + if (id.isPresent()) { + return "ID: " + id.get(); + } else { + return "ID missing"; + } + } + + @GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" }) + @ResponseBody + public String getEmployeesByIdWithMap(@PathVariable Map pathVarsMap) { + String id = pathVarsMap.get("id"); + if (id != null) { + return "ID: " + id; + } else { + return "ID missing"; + } + } +} From 3433279c30d3d7fc15545259dce8407a3e2b0390 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 20 Jul 2020 20:04:15 +0430 Subject: [PATCH 061/155] A Guide to BitSet in Java --- .../core-java-collections-3/pom.xml | 6 + .../collections/bitset/BitSetUnitTest.java | 152 ++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml index b206cd61d2..a9a05f5092 100644 --- a/core-java-modules/core-java-collections-3/pom.xml +++ b/core-java-modules/core-java-collections-3/pom.xml @@ -16,6 +16,11 @@ + + org.openjdk.jol + jol-core + ${jol-core.version} + org.openjdk.jmh jmh-core @@ -37,6 +42,7 @@ 1.19 3.11.1 + 0.10 diff --git a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java new file mode 100644 index 0000000000..d6e5f23f4e --- /dev/null +++ b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java @@ -0,0 +1,152 @@ +package com.baeldung.collections.bitset; + +import org.junit.Test; +import org.openjdk.jol.info.ClassLayout; +import org.openjdk.jol.info.GraphLayout; + +import java.util.BitSet; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BitSetUnitTest { + + @Test + public void givenBoolArray_whenMemoryLayout_thenConsumeMoreThanOneBit() { + boolean[] bits = new boolean[1024]; + + System.out.println(ClassLayout.parseInstance(bits).toPrintable()); + } + + @Test + public void givenBitSet_whenMemoryLayout_thenConsumeObeBitPerFlag() { + BitSet bitSet = new BitSet(1024); + + System.out.println(GraphLayout.parseInstance(bitSet).toPrintable()); + } + + @Test + public void givenBitSet_whenSetting_thenShouldBeTrue() { + BitSet bitSet = new BitSet(); + + bitSet.set(10); + assertThat(bitSet.get(10)).isTrue(); + + bitSet.set(20, 30); + for (int i = 20; i <= 29; i++) assertThat(bitSet.get(i)).isTrue(); + assertThat(bitSet.get(30)).isFalse(); + + bitSet.set(10, false); + assertThat(bitSet.get(10)).isFalse(); + + bitSet.set(20, 30, false); + for (int i = 20; i <= 30; i++) assertThat(bitSet.get(i)).isFalse(); + } + + @Test + public void givenBitSet_whenClearing_thenShouldBeFalse() { + BitSet bitSet = new BitSet(); + bitSet.set(42); + assertThat(bitSet.get(42)).isTrue(); + + bitSet.clear(42); + assertThat(bitSet.get(42)).isFalse(); + + bitSet.set(10, 20); + for (int i = 10; i < 20; i++) assertThat(bitSet.get(i)).isTrue(); + + bitSet.clear(10, 20); + for (int i = 10; i < 20; i++) assertThat(bitSet.get(i)).isFalse(); + + bitSet.set(10, 20); + bitSet.clear(); + for (int i = 0; i < 100; i++) assertThat(bitSet.get(i)).isFalse(); + } + + @Test + public void givenBitSet_whenGettingElements_thenShouldReturnRequestedBits() { + BitSet bitSet = new BitSet(); + bitSet.set(42); + + assertThat(bitSet.get(42)).isTrue(); + assertThat(bitSet.get(43)).isFalse(); + + bitSet.set(10, 20); + BitSet newBitSet = bitSet.get(10, 20); + for (int i = 0; i < 10; i++) assertThat(newBitSet.get(i)).isTrue(); + } + + @Test + public void givenBitSet_whenFlip_thenTogglesTrueToFalseAndViceVersa() { + BitSet bitSet = new BitSet(); + bitSet.set(42); + bitSet.flip(42); + assertThat(bitSet.get(42)).isFalse(); + + bitSet.flip(12); + assertThat(bitSet.get(12)).isTrue(); + + bitSet.flip(30, 40); + for (int i = 30; i < 40; i++) assertThat(bitSet.get(i)).isTrue(); + } + + @Test + public void givenBitSet_whenGettingTheSize_thenReturnsTheSize() { + BitSet defaultBitSet = new BitSet(); + assertThat(defaultBitSet.size()).isEqualTo(64); + + BitSet bitSet = new BitSet(1024); + assertThat(bitSet.size()).isEqualTo(1024); + + assertThat(bitSet.cardinality()).isEqualTo(0); + bitSet.set(10, 30); + assertThat(bitSet.cardinality()).isEqualTo(30 - 10); + + assertThat(bitSet.length()).isEqualTo(30); + bitSet.set(100); + assertThat(bitSet.length()).isEqualTo(101); + + assertThat(bitSet.isEmpty()).isFalse(); + bitSet.clear(); + assertThat(bitSet.isEmpty()).isTrue(); + } + + @Test + public void givenBitSet_whenSetOperations_thenShouldReturnAnotherBitSet() { + BitSet first = new BitSet(); + first.set(5, 10); + + BitSet second = new BitSet(); + second.set(7, 15); + + assertThat(first.intersects(second)).isTrue(); + + first.and(second); + assertThat(first.get(7)).isTrue(); + assertThat(first.get(8)).isTrue(); + assertThat(first.get(9)).isTrue(); + assertThat(first.get(10)).isFalse(); + } + + @Test + public void givenBitSet_whenStream_thenStreamsAllSetBits() { + BitSet bitSet = new BitSet(); + bitSet.set(15, 25); + + bitSet.stream().forEach(System.out::println); + } + + @Test + public void givenBitSet_whenNextOrPrev_thenReturnsTheNextClearOrSetBit() { + BitSet bitSet = new BitSet(); + bitSet.set(15, 25); + + assertThat(bitSet.nextSetBit(13)).isEqualTo(15); + assertThat(bitSet.nextSetBit(25)).isEqualTo(-1); + + assertThat(bitSet.nextClearBit(23)).isEqualTo(25); + + assertThat(bitSet.previousClearBit(24)).isEqualTo(14); + assertThat(bitSet.previousSetBit(29)).isEqualTo(24); + assertThat(bitSet.previousSetBit(14)).isEqualTo(-1); + } +} From bacce9abc8f57591dbb26d4309469a4388567078 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 20 Jul 2020 20:07:37 +0430 Subject: [PATCH 062/155] Polish. --- .../java/com/baeldung/collections/bitset/BitSetUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java index d6e5f23f4e..6c677e4b0e 100644 --- a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java +++ b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java @@ -18,7 +18,7 @@ public class BitSetUnitTest { } @Test - public void givenBitSet_whenMemoryLayout_thenConsumeObeBitPerFlag() { + public void givenBitSet_whenMemoryLayout_thenConsumeOneBitPerFlag() { BitSet bitSet = new BitSet(1024); System.out.println(GraphLayout.parseInstance(bitSet).toPrintable()); @@ -136,7 +136,7 @@ public class BitSetUnitTest { } @Test - public void givenBitSet_whenNextOrPrev_thenReturnsTheNextClearOrSetBit() { + public void givenBitSet_whenNextOrPrev_thenReturnsTheNextOrPrevClearOrSetBit() { BitSet bitSet = new BitSet(); bitSet.set(15, 25); From 030fa1b52340c0e08ad9bd60da14ac3c660388c7 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Mon, 20 Jul 2020 21:00:35 +0430 Subject: [PATCH 063/155] Polish. --- .../baeldung/collections/bitset/BitSetUnitTest.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java index 6c677e4b0e..74aa224a49 100644 --- a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java +++ b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java @@ -12,14 +12,14 @@ public class BitSetUnitTest { @Test public void givenBoolArray_whenMemoryLayout_thenConsumeMoreThanOneBit() { - boolean[] bits = new boolean[1024]; + boolean[] bits = new boolean[1024 * 1024]; System.out.println(ClassLayout.parseInstance(bits).toPrintable()); } @Test public void givenBitSet_whenMemoryLayout_thenConsumeOneBitPerFlag() { - BitSet bitSet = new BitSet(1024); + BitSet bitSet = new BitSet(1024 * 1024); System.out.println(GraphLayout.parseInstance(bitSet).toPrintable()); } @@ -125,6 +125,13 @@ public class BitSetUnitTest { assertThat(first.get(8)).isTrue(); assertThat(first.get(9)).isTrue(); assertThat(first.get(10)).isFalse(); + + first.clear(); + first.set(5, 10); + + first.xor(second); + for (int i = 5; i < 7; i++) assertThat(first.get(i)).isTrue(); + for (int i = 10; i < 15; i++) assertThat(first.get(i)).isTrue(); } @Test @@ -133,6 +140,7 @@ public class BitSetUnitTest { bitSet.set(15, 25); bitSet.stream().forEach(System.out::println); + assertThat(bitSet.stream().count()).isEqualTo(10); } @Test From 289276f8ff9ca11d30036d8673fbaddb9f36409c Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 21 Jul 2020 06:36:14 +0200 Subject: [PATCH 064/155] Revert "[BAEL-4281] Examples of array comparisons" This reverts commit d1a9ff7480f8f21543c02d61992d0dd20fa4e56d. --- java-collections/README.md | 8 --- java-collections/pom.xml | 49 ------------------- .../com/baeldung/comparingarrays/Plane.java | 39 --------------- .../src/main/resources/logback.xml | 13 ----- .../baeldung/DeepEqualsCompareUnitTest.java | 34 ------------- .../com/baeldung/EqualsCompareUnitTest.java | 29 ----------- .../com/baeldung/LengthsCompareUnitTest.java | 22 --------- .../com/baeldung/OrderCompareUnitTest.java | 34 ------------- .../baeldung/ReferenceCompareUnitTest.java | 34 ------------- 9 files changed, 262 deletions(-) delete mode 100644 java-collections/README.md delete mode 100644 java-collections/pom.xml delete mode 100644 java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java delete mode 100644 java-collections/src/main/resources/logback.xml delete mode 100644 java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java delete mode 100644 java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java delete mode 100644 java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java delete mode 100644 java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java delete mode 100644 java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java diff --git a/java-collections/README.md b/java-collections/README.md deleted file mode 100644 index 480b7f257a..0000000000 --- a/java-collections/README.md +++ /dev/null @@ -1,8 +0,0 @@ -## Java Collections Examples - -This module support code for articles about handling java collections and arrays. - -### Relevant Articles: -- [Comparing two integer arrays in Java](https://stackoverflow.com/questions/14897366/comparing-two-integer-arrays-in-java) -- [Compare two arrays with not the same order](https://stackoverflow.com/questions/54711228/compare-two-arrays-with-not-the-same-order) -- More articles: [[next -->]](../java-collections-conversions-2) \ No newline at end of file diff --git a/java-collections/pom.xml b/java-collections/pom.xml deleted file mode 100644 index 5e0ee42244..0000000000 --- a/java-collections/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - java-collections - 0.1.0-SNAPSHOT - java-collections - jar - - - com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java - - - - - org.apache.commons - commons-collections4 - ${commons-collections4.version} - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - org.hamcrest - hamcrest-all - ${hamcrest-all.version} - test - - - - - java-collections - - - src/main/resources - true - - - - - - 4.1 - - diff --git a/java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java b/java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java deleted file mode 100644 index db61807878..0000000000 --- a/java-collections/src/main/java/com/baeldung/comparingarrays/Plane.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.baeldung.comparingarrays; - -import java.util.Objects; - -public class Plane { - - private final String name; - - private final String model; - - public Plane(String name, String model) { - - this.name = name; - this.model = model; - } - - public String getName() { - return name; - } - - public String getModel() { - return model; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Plane plane = (Plane) o; - return Objects.equals(name, plane.name) && Objects.equals(model, plane.model); - } - - @Override - public int hashCode() { - return Objects.hash(name, model); - } -} diff --git a/java-collections/src/main/resources/logback.xml b/java-collections/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/java-collections/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java deleted file mode 100644 index f311d0e5c9..0000000000 --- a/java-collections/src/test/java/com/baeldung/DeepEqualsCompareUnitTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung; - -import com.baeldung.comparingarrays.Plane; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class DeepEqualsCompareUnitTest { - - @Test - public void givenArray1andArray2_whenSameContent_thenDeepEquals() { - final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, - new Plane[] { new Plane("Plane 2", "B738") } }; - final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, - new Plane[] { new Plane("Plane 2", "B738") } }; - - boolean result = Arrays.deepEquals(planes1, planes2); - assertTrue("Result is not true", result); - } - - @Test - public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { - final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, - new Plane[] { new Plane("Plane 2", "B738") } }; - final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") }, - new Plane[] { new Plane("Plane 1", "A320") } }; - - boolean result = Arrays.deepEquals(planes1, planes2); - assertFalse("Result is true", result); - } -} diff --git a/java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java deleted file mode 100644 index b56395a848..0000000000 --- a/java-collections/src/test/java/com/baeldung/EqualsCompareUnitTest.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung; - -import org.junit.jupiter.api.Test; - -import java.util.Arrays; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class EqualsCompareUnitTest { - - @Test - public void givenArray1andArray2_whenSameContent_thenEquals() { - final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - - boolean result = Arrays.equals(planes1, planes2); - assertTrue("Result is not true", result); - } - - @Test - public void givenArray1andArray2_whenSameContentOtherSort_thenNotEquals() { - final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" }; - - boolean result = Arrays.equals(planes1, planes2); - assertFalse("Result is true", result); - } -} diff --git a/java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java deleted file mode 100644 index 8b3c90c427..0000000000 --- a/java-collections/src/test/java/com/baeldung/LengthsCompareUnitTest.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung; - -import org.junit.jupiter.api.Test; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; -import static org.junit.Assert.assertThat; - -public class LengthsCompareUnitTest { - - @Test - public void givenArray1andArray2_whenSameSizes_thenSizeEqualsOk() { - final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 }; - - assertThat(planes1, arrayWithSize(8)); - assertThat(quantities, arrayWithSize(8)); - assertThat(planes1.length, is(8)); - assertThat(quantities.length, is(8)); - } -} - diff --git a/java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java deleted file mode 100644 index 8be7251c05..0000000000 --- a/java-collections/src/test/java/com/baeldung/OrderCompareUnitTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung; - -import com.baeldung.comparingarrays.Plane; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Comparator; - -import static org.junit.Assert.assertTrue; - -public class OrderCompareUnitTest { - @Test - public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { - final Plane[][] planes1 = new Plane[][] { - new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } }; - final Plane[][] planes2 = new Plane[][] { - new Plane[] { new Plane("Plane 2", "B738"), new Plane("Plane 1", "A320") } }; - - Comparator planeComparator = (o1, o2) -> { - if (o1.getName() - .equals(o2.getName())) { - return o2.getModel() - .compareTo(o1.getModel()); - } - return o2.getName() - .compareTo(o1.getName()); - }; - Arrays.sort(planes1[0], planeComparator); - Arrays.sort(planes2[0], planeComparator); - - boolean result = Arrays.deepEquals(planes1, planes2); - assertTrue("Result is false", result); - } -} diff --git a/java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java b/java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java deleted file mode 100644 index 9716a34607..0000000000 --- a/java-collections/src/test/java/com/baeldung/ReferenceCompareUnitTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung; - -import org.junit.jupiter.api.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; - -public class ReferenceCompareUnitTest { - - @Test - public void givenArray1andArray2_whenEquals_thenEqual() { - final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - final String[] planes2 = planes1; - - assertSame("Objects are not equal!", planes1, planes2); - - planes2[0] = "747"; - - assertSame("Objects are not same!", planes1, planes2); - assertEquals("Objects are not equal!", "747", planes2[0]); - assertEquals("Objects are not equal!", "747", planes1[0]); - } - - @Test - public void givenArray1andArray2_whenDifferentValues_thenNotEqual() { - final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - - assertNotSame("Objects are the same!", planes1, planes2); - assertNotEquals("Objects are equal!", planes1, planes2); - } -} From ad1d9b4b847270082314659ad2736c6ee0f2fe14 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 21 Jul 2020 06:37:09 +0200 Subject: [PATCH 065/155] [BAEL-4281] moves example module --- .../java/com/baeldung/arraycompare/Plane.java | 39 +++++++++++++++++++ .../DeepEqualsCompareUnitTest.java | 33 ++++++++++++++++ .../arraycompare/EqualsCompareUnitTest.java | 29 ++++++++++++++ .../arraycompare/LengthsCompareUnitTest.java | 22 +++++++++++ .../arraycompare/OrderCompareUnitTest.java | 33 ++++++++++++++++ .../ReferenceCompareUnitTest.java | 34 ++++++++++++++++ 6 files changed, 190 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycompare/Plane.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycompare/Plane.java b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycompare/Plane.java new file mode 100644 index 0000000000..1731578b76 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/main/java/com/baeldung/arraycompare/Plane.java @@ -0,0 +1,39 @@ +package com.baeldung.arraycompare; + +import java.util.Objects; + +public class Plane { + + private final String name; + + private final String model; + + public Plane(String name, String model) { + + this.name = name; + this.model = model; + } + + public String getName() { + return name; + } + + public String getModel() { + return model; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Plane plane = (Plane) o; + return Objects.equals(name, plane.name) && Objects.equals(model, plane.model); + } + + @Override + public int hashCode() { + return Objects.hash(name, model); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java new file mode 100644 index 0000000000..ab7eaec127 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.arraycompare; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class DeepEqualsCompareUnitTest { + + @Test + public void givenArray1andArray2_whenSameContent_thenDeepEquals() { + final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, + new Plane[] { new Plane("Plane 2", "B738") } }; + final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, + new Plane[] { new Plane("Plane 2", "B738") } }; + + boolean result = Arrays.deepEquals(planes1, planes2); + assertTrue("Result is not true", result); + } + + @Test + public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { + final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, + new Plane[] { new Plane("Plane 2", "B738") } }; + final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") }, + new Plane[] { new Plane("Plane 1", "A320") } }; + + boolean result = Arrays.deepEquals(planes1, planes2); + assertFalse("Result is true", result); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java new file mode 100644 index 0000000000..dd74eb8f0a --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.arraycompare; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class EqualsCompareUnitTest { + + @Test + public void givenArray1andArray2_whenSameContent_thenEquals() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + + boolean result = Arrays.equals(planes1, planes2); + assertTrue("Result is not true", result); + } + + @Test + public void givenArray1andArray2_whenSameContentOtherSort_thenNotEquals() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" }; + + boolean result = Arrays.equals(planes1, planes2); + assertFalse("Result is true", result); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java new file mode 100644 index 0000000000..ef22d69d90 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java @@ -0,0 +1,22 @@ +package com.baeldung.arraycompare; + +import org.junit.jupiter.api.Test; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; +import static org.junit.Assert.assertThat; + +public class LengthsCompareUnitTest { + + @Test + public void givenArray1andArray2_whenSameSizes_thenSizeEqualsOk() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 }; + + assertThat(planes1, arrayWithSize(8)); + assertThat(quantities, arrayWithSize(8)); + assertThat(planes1.length, is(8)); + assertThat(quantities.length, is(8)); + } +} + diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java new file mode 100644 index 0000000000..77cc91092a --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.arraycompare; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Comparator; + +import static org.junit.Assert.assertTrue; + +public class OrderCompareUnitTest { + @Test + public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { + final Plane[][] planes1 = new Plane[][] { + new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } }; + final Plane[][] planes2 = new Plane[][] { + new Plane[] { new Plane("Plane 2", "B738"), new Plane("Plane 1", "A320") } }; + + Comparator planeComparator = (o1, o2) -> { + if (o1.getName() + .equals(o2.getName())) { + return o2.getModel() + .compareTo(o1.getModel()); + } + return o2.getName() + .compareTo(o1.getName()); + }; + Arrays.sort(planes1[0], planeComparator); + Arrays.sort(planes2[0], planeComparator); + + boolean result = Arrays.deepEquals(planes1, planes2); + assertTrue("Result is false", result); + } +} diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java new file mode 100644 index 0000000000..8a26fc8e74 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.arraycompare; + +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; + +public class ReferenceCompareUnitTest { + + @Test + public void givenArray1andArray2_whenEquals_thenEqual() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = planes1; + + assertSame("Objects are not equal!", planes1, planes2); + + planes2[0] = "747"; + + assertSame("Objects are not same!", planes1, planes2); + assertEquals("Objects are not equal!", "747", planes2[0]); + assertEquals("Objects are not equal!", "747", planes1[0]); + } + + @Test + public void givenArray1andArray2_whenDifferentValues_thenNotEqual() { + final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; + + assertNotSame("Objects are the same!", planes1, planes2); + assertNotEquals("Objects are equal!", planes1, planes2); + } +} From cffc591b5cd84ef056bc90d5e3a3d087d8882850 Mon Sep 17 00:00:00 2001 From: Joao Esperancinha Date: Tue, 21 Jul 2020 06:55:28 +0200 Subject: [PATCH 066/155] [BAEL-4281] Naming convention and conversion to assertJ --- .../DeepEqualsCompareUnitTest.java | 13 +++++------- .../arraycompare/EqualsCompareUnitTest.java | 13 +++++------- .../arraycompare/LengthsCompareUnitTest.java | 12 ++++------- .../arraycompare/OrderCompareUnitTest.java | 6 +++--- .../ReferenceCompareUnitTest.java | 20 ++++++++----------- 5 files changed, 25 insertions(+), 39 deletions(-) diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java index ab7eaec127..c8ebafb26b 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/DeepEqualsCompareUnitTest.java @@ -4,30 +4,27 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class DeepEqualsCompareUnitTest { @Test - public void givenArray1andArray2_whenSameContent_thenDeepEquals() { + public void givenSameContents_whenDeepEquals_thenTrue() { final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, new Plane[] { new Plane("Plane 2", "B738") } }; final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, new Plane[] { new Plane("Plane 2", "B738") } }; - boolean result = Arrays.deepEquals(planes1, planes2); - assertTrue("Result is not true", result); + assertThat(Arrays.deepEquals(planes1, planes2)).isTrue(); } @Test - public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { + public void givenSameContentsWithDifferentOrder_whenDeepEquals_thenFalse() { final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320") }, new Plane[] { new Plane("Plane 2", "B738") } }; final Plane[][] planes2 = new Plane[][] { new Plane[] { new Plane("Plane 2", "B738") }, new Plane[] { new Plane("Plane 1", "A320") } }; - boolean result = Arrays.deepEquals(planes1, planes2); - assertFalse("Result is true", result); + assertThat(Arrays.deepEquals(planes1, planes2)).isFalse(); } } diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java index dd74eb8f0a..a022bf7082 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/EqualsCompareUnitTest.java @@ -4,26 +4,23 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class EqualsCompareUnitTest { @Test - public void givenArray1andArray2_whenSameContent_thenEquals() { + public void givenSameContents_whenEquals_thenTrue() { final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - boolean result = Arrays.equals(planes1, planes2); - assertTrue("Result is not true", result); + assertThat(Arrays.equals(planes1, planes2)).isTrue(); } @Test - public void givenArray1andArray2_whenSameContentOtherSort_thenNotEquals() { + public void givenSameContentsDifferentOrder_whenEquals_thenFalse() { final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; final String[] planes2 = new String[] { "B738", "A320", "A321", "A319", "B77W", "B737", "A333", "A332" }; - boolean result = Arrays.equals(planes1, planes2); - assertFalse("Result is true", result); + assertThat(Arrays.equals(planes1, planes2)).isFalse(); } } diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java index ef22d69d90..23187b827c 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/LengthsCompareUnitTest.java @@ -2,21 +2,17 @@ package com.baeldung.arraycompare; import org.junit.jupiter.api.Test; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.collection.IsArrayWithSize.arrayWithSize; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; public class LengthsCompareUnitTest { @Test - public void givenArray1andArray2_whenSameSizes_thenSizeEqualsOk() { + public void givenSameContent_whenSizeCompare_thenTrue() { final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; final Integer[] quantities = new Integer[] { 10, 12, 34, 45, 12, 43, 5, 2 }; - assertThat(planes1, arrayWithSize(8)); - assertThat(quantities, arrayWithSize(8)); - assertThat(planes1.length, is(8)); - assertThat(quantities.length, is(8)); + assertThat(planes1).hasSize(8); + assertThat(quantities).hasSize(8); } } diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java index 77cc91092a..4dd7964020 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/OrderCompareUnitTest.java @@ -5,11 +5,12 @@ import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Comparator; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; public class OrderCompareUnitTest { @Test - public void givenArray1andArray2_whenNotSameContent_thenNotDeepEquals() { + public void givenSameContentDifferentOrder_whenSortedAndDeepEquals_thenTrue() { final Plane[][] planes1 = new Plane[][] { new Plane[] { new Plane("Plane 1", "A320"), new Plane("Plane 2", "B738") } }; final Plane[][] planes2 = new Plane[][] { @@ -27,7 +28,6 @@ public class OrderCompareUnitTest { Arrays.sort(planes1[0], planeComparator); Arrays.sort(planes2[0], planeComparator); - boolean result = Arrays.deepEquals(planes1, planes2); - assertTrue("Result is false", result); + assertThat(Arrays.deepEquals(planes1, planes2)).isTrue(); } } diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java index 8a26fc8e74..d8072a98e3 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ReferenceCompareUnitTest.java @@ -2,33 +2,29 @@ package com.baeldung.arraycompare; import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; public class ReferenceCompareUnitTest { @Test - public void givenArray1andArray2_whenEquals_thenEqual() { + public void givenSameReferences_whenSame_thenTrue() { final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; final String[] planes2 = planes1; - assertSame("Objects are not equal!", planes1, planes2); + assertThat(planes1).isSameAs(planes2); planes2[0] = "747"; - assertSame("Objects are not same!", planes1, planes2); - assertEquals("Objects are not equal!", "747", planes2[0]); - assertEquals("Objects are not equal!", "747", planes1[0]); + assertThat(planes1).isSameAs(planes2); + assertThat(planes2[0]).isEqualTo("747"); + assertThat(planes1[0]).isEqualTo("747"); } @Test - public void givenArray1andArray2_whenDifferentValues_thenNotEqual() { + public void givenSameContentDifferentReferences_whenSame_thenFalse() { final String[] planes1 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; final String[] planes2 = new String[] { "A320", "B738", "A321", "A319", "B77W", "B737", "A333", "A332" }; - assertNotSame("Objects are the same!", planes1, planes2); - assertNotEquals("Objects are equal!", planes1, planes2); + assertThat(planes1).isNotSameAs(planes2); } } From f9917c483f3a37b1db1617f85b71c24f5095ff03 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Tue, 21 Jul 2020 12:59:14 +0530 Subject: [PATCH 067/155] Delete index.html --- .../http-session-example/WebContent/index.html | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 spring-session/http-session-example/WebContent/index.html diff --git a/spring-session/http-session-example/WebContent/index.html b/spring-session/http-session-example/WebContent/index.html deleted file mode 100644 index 063d330854..0000000000 --- a/spring-session/http-session-example/WebContent/index.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - -Insert title here - - -
-Name:

- -
- - \ No newline at end of file From 75eba2fa7d17be3afe0b76b33b23c49dc1d84a4d Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Tue, 21 Jul 2020 12:59:32 +0530 Subject: [PATCH 068/155] Delete web.xml --- .../WebContent/WEB-INF/web.xml | 29 ------------------- 1 file changed, 29 deletions(-) delete mode 100644 spring-session/http-session-example/WebContent/WEB-INF/web.xml diff --git a/spring-session/http-session-example/WebContent/WEB-INF/web.xml b/spring-session/http-session-example/WebContent/WEB-INF/web.xml deleted file mode 100644 index 01b1b6f308..0000000000 --- a/spring-session/http-session-example/WebContent/WEB-INF/web.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - httpsessionexample - - index.html - - - -firstservlet -httpsessionexample.FirstServlet - - - -firstservlet -/firstservlet - - - -secondservlet -httpsessionexample.SecondServlet - - - -secondservlet -/secondservlet - - - - From 8b16479fd96f9888542d6a9d052fe0d5144e1b24 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Tue, 21 Jul 2020 12:59:53 +0530 Subject: [PATCH 069/155] Delete FirstServlet.java --- .../src/httpsessionexample/FirstServlet.java | 33 ------------------- 1 file changed, 33 deletions(-) delete mode 100644 spring-session/http-session-example/src/httpsessionexample/FirstServlet.java diff --git a/spring-session/http-session-example/src/httpsessionexample/FirstServlet.java b/spring-session/http-session-example/src/httpsessionexample/FirstServlet.java deleted file mode 100644 index d49c0f3e14..0000000000 --- a/spring-session/http-session-example/src/httpsessionexample/FirstServlet.java +++ /dev/null @@ -1,33 +0,0 @@ -package httpsessionexample; - -import java.io.PrintWriter; - -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -public class FirstServlet extends HttpServlet { - public void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - HttpSession session = request.getSession(); - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - - String name = request.getParameter("userName"); - out.print("Hi " + name); - - session.setAttribute("uname", name); - out.print("
"); - out.print("Session Id : " + session.getId()); - out.print("
"); - out.print("Second Servlet"); - - out.close(); - - } catch (Exception e) { - System.out.println(e); - } - } - -} From 7ff9bc6ac811d0ee2a6623d102bbb850ce09bc64 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Tue, 21 Jul 2020 13:00:09 +0530 Subject: [PATCH 070/155] Delete SecondServlet.java --- .../src/httpsessionexample/SecondServlet.java | 31 ------------------- 1 file changed, 31 deletions(-) delete mode 100644 spring-session/http-session-example/src/httpsessionexample/SecondServlet.java diff --git a/spring-session/http-session-example/src/httpsessionexample/SecondServlet.java b/spring-session/http-session-example/src/httpsessionexample/SecondServlet.java deleted file mode 100644 index ab0b9c34ad..0000000000 --- a/spring-session/http-session-example/src/httpsessionexample/SecondServlet.java +++ /dev/null @@ -1,31 +0,0 @@ -package httpsessionexample; - -import java.io.PrintWriter; - -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -public class SecondServlet extends HttpServlet { - - public void doGet(HttpServletRequest request, HttpServletResponse response) { - try { - - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - - HttpSession session = request.getSession(true); - String name = (String) session.getAttribute("uname"); - out.print("Hi " + name); - out.print("
"); - out.print("Session Id : " + session.getId()); - out.print("
"); - out.close(); - - } catch (Exception e) { - System.out.println(e); - } - } - -} From ccfbdd3f9c990a644e03903ab67abeadfdc7835f Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Tue, 21 Jul 2020 13:00:59 +0530 Subject: [PATCH 071/155] Add files via upload --- spring-session/http-session-example/README.md | 5 +++ spring-session/http-session-example/pom.xml | 26 +++++++++++++++ .../baeldung/httpsession/FirstServlet.java | 33 +++++++++++++++++++ .../baeldung/httpsession/SecondServlet.java | 31 +++++++++++++++++ .../src/main/webapp/WEB-INF/web.xml | 33 +++++++++++++++++++ .../src/main/webapp/index.html | 12 +++++++ 6 files changed, 140 insertions(+) create mode 100644 spring-session/http-session-example/README.md create mode 100644 spring-session/http-session-example/pom.xml create mode 100644 spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java create mode 100644 spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java create mode 100644 spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml create mode 100644 spring-session/http-session-example/src/main/webapp/index.html diff --git a/spring-session/http-session-example/README.md b/spring-session/http-session-example/README.md new file mode 100644 index 0000000000..95c7a41e2d --- /dev/null +++ b/spring-session/http-session-example/README.md @@ -0,0 +1,5 @@ +## HttpSession + +This module contains article about Difference Between request.getSession() and request.getSession(true) + +### Relevant Articles: diff --git a/spring-session/http-session-example/pom.xml b/spring-session/http-session-example/pom.xml new file mode 100644 index 0000000000..a77176fb4b --- /dev/null +++ b/spring-session/http-session-example/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + com.baeldung.httpsession + http-session-example + war + 0.0.1-SNAPSHOT + http-session-example Maven Webapp + http://maven.apache.org + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + javax.servlet + servlet-api + 2.5 + provided + + + diff --git a/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java b/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java new file mode 100644 index 0000000000..950bea2c07 --- /dev/null +++ b/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java @@ -0,0 +1,33 @@ +package com.baeldung.httpsession; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class FirstServlet extends HttpServlet { + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + try { + HttpSession session = request.getSession(); + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + String name = request.getParameter("userName"); + session.setAttribute("uname", name); + out.println("Hi " + name + " Your Session Id is : " + session.getId() + " "); + + out.println("
Second Servlet"); + + out.close(); + + } catch (Exception e) { + System.out.println(e); + } + } + +} diff --git a/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java b/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java new file mode 100644 index 0000000000..6a5ef7e9a8 --- /dev/null +++ b/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java @@ -0,0 +1,31 @@ +package com.baeldung.httpsession; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class SecondServlet extends HttpServlet { + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + try { + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + HttpSession session = request.getSession(true); + String name = (String) session.getAttribute("uname"); + out.println("Hi " + name + " Your Session Id is : " + session.getId()); + + out.close(); + + } catch (Exception e) { + System.out.println(e); + } + } + +} diff --git a/spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml b/spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..2c9a4c118b --- /dev/null +++ b/spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,33 @@ + + + + httpsession + + index.html + + + + + FirstServlet + com.baeldung.httpsession.FirstServlet + + + SecondServlet + com.baeldung.httpsession.SecondServlet + + + + + FirstServlet + /first + + + SecondServlet + /second + + + + \ No newline at end of file diff --git a/spring-session/http-session-example/src/main/webapp/index.html b/spring-session/http-session-example/src/main/webapp/index.html new file mode 100644 index 0000000000..0e5889f21a --- /dev/null +++ b/spring-session/http-session-example/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + + + +
+ Name:

+
+ + \ No newline at end of file From 4c4b784d02397a299896961304dbb279160a5eaa Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Tue, 21 Jul 2020 20:24:51 +0200 Subject: [PATCH 072/155] JAVA-1649: Get rid of the overriden spring-boot.version property --- spring-security-modules/spring-security-oidc/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-security-modules/spring-security-oidc/pom.xml b/spring-security-modules/spring-security-oidc/pom.xml index 91e4641450..b9a4b340a3 100644 --- a/spring-security-modules/spring-security-oidc/pom.xml +++ b/spring-security-modules/spring-security-oidc/pom.xml @@ -26,8 +26,4 @@
- - 2.2.1.RELEASE - - From ab755bf0988833e15380c4c1c8c1fb89cea1b984 Mon Sep 17 00:00:00 2001 From: developerDiv Date: Tue, 21 Jul 2020 21:32:40 +0100 Subject: [PATCH 073/155] Add static class to 'eq' and 'when' for greater readability. --- .../argumentcaptor/EmailServiceUnitTest.java | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index 2208bc7c7b..9d18957b2e 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -2,16 +2,10 @@ package com.baeldung.mockito.argumentcaptor; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; +import org.mockito.*; import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class EmailServiceUnitTest { @@ -36,7 +30,7 @@ public class EmailServiceUnitTest { emailService.send(to, subject, body, false); - verify(platform).send(emailCaptor.capture()); + Mockito.verify(platform).send(emailCaptor.capture()); Email emailCaptorValue = emailCaptor.getValue(); assertEquals(Format.TEXT_ONLY, emailCaptorValue.getFormat()); } @@ -49,14 +43,14 @@ public class EmailServiceUnitTest { emailService.send(to, subject, body, true); - verify(platform).send(emailCaptor.capture()); + Mockito.verify(platform).send(emailCaptor.capture()); Email value = emailCaptor.getValue(); assertEquals(Format.HTML, value.getFormat()); } @Test public void whenServiceRunning_expectUpResponse() { - when(platform.getServiceStatus()).thenReturn("OK"); + Mockito.when(platform.getServiceStatus()).thenReturn("OK"); ServiceStatus serviceStatus = emailService.checkServiceStatus(); @@ -65,7 +59,7 @@ public class EmailServiceUnitTest { @Test public void whenServiceNotRunning_expectDownResponse() { - when(platform.getServiceStatus()).thenReturn("Error"); + Mockito.when(platform.getServiceStatus()).thenReturn("Error"); ServiceStatus serviceStatus = emailService.checkServiceStatus(); @@ -75,15 +69,15 @@ public class EmailServiceUnitTest { @Test public void usingArgumentMatcher_whenAuthenticatedWithValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); + Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); assertTrue(emailService.authenticatedSuccessfully(credentials)); } @Test - public void usingArgumentCapture_whenAuthenticatedWithValidCredentials_expectTrue() { + public void usingArgumentCaptor_whenAuthenticatedWithValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); - when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); + Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); assertTrue(emailService.authenticatedSuccessfully(credentials)); assertEquals(credentials, credentialsCaptor.getValue()); @@ -92,7 +86,7 @@ public class EmailServiceUnitTest { @Test public void whenNotAuthenticated_expectFalse() { Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key"); - when(platform.authenticate(eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); + Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED); assertFalse(emailService.authenticatedSuccessfully(credentials)); } From a72f2f144cbd2d446e16860b72995f5f048b5e2c Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Wed, 22 Jul 2020 19:43:35 +0430 Subject: [PATCH 074/155] Switching the For Blocks! --- .../collections/bitset/BitSetUnitTest.java | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java index 74aa224a49..d9340f45c1 100644 --- a/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java +++ b/core-java-modules/core-java-collections-3/src/test/java/com/baeldung/collections/bitset/BitSetUnitTest.java @@ -32,14 +32,18 @@ public class BitSetUnitTest { assertThat(bitSet.get(10)).isTrue(); bitSet.set(20, 30); - for (int i = 20; i <= 29; i++) assertThat(bitSet.get(i)).isTrue(); + for (int i = 20; i <= 29; i++) { + assertThat(bitSet.get(i)).isTrue(); + } assertThat(bitSet.get(30)).isFalse(); bitSet.set(10, false); assertThat(bitSet.get(10)).isFalse(); bitSet.set(20, 30, false); - for (int i = 20; i <= 30; i++) assertThat(bitSet.get(i)).isFalse(); + for (int i = 20; i <= 30; i++) { + assertThat(bitSet.get(i)).isFalse(); + } } @Test @@ -52,14 +56,20 @@ public class BitSetUnitTest { assertThat(bitSet.get(42)).isFalse(); bitSet.set(10, 20); - for (int i = 10; i < 20; i++) assertThat(bitSet.get(i)).isTrue(); + for (int i = 10; i < 20; i++) { + assertThat(bitSet.get(i)).isTrue(); + } bitSet.clear(10, 20); - for (int i = 10; i < 20; i++) assertThat(bitSet.get(i)).isFalse(); + for (int i = 10; i < 20; i++) { + assertThat(bitSet.get(i)).isFalse(); + } bitSet.set(10, 20); bitSet.clear(); - for (int i = 0; i < 100; i++) assertThat(bitSet.get(i)).isFalse(); + for (int i = 0; i < 100; i++) { + assertThat(bitSet.get(i)).isFalse(); + } } @Test @@ -72,7 +82,9 @@ public class BitSetUnitTest { bitSet.set(10, 20); BitSet newBitSet = bitSet.get(10, 20); - for (int i = 0; i < 10; i++) assertThat(newBitSet.get(i)).isTrue(); + for (int i = 0; i < 10; i++) { + assertThat(newBitSet.get(i)).isTrue(); + } } @Test @@ -86,7 +98,9 @@ public class BitSetUnitTest { assertThat(bitSet.get(12)).isTrue(); bitSet.flip(30, 40); - for (int i = 30; i < 40; i++) assertThat(bitSet.get(i)).isTrue(); + for (int i = 30; i < 40; i++) { + assertThat(bitSet.get(i)).isTrue(); + } } @Test @@ -130,8 +144,12 @@ public class BitSetUnitTest { first.set(5, 10); first.xor(second); - for (int i = 5; i < 7; i++) assertThat(first.get(i)).isTrue(); - for (int i = 10; i < 15; i++) assertThat(first.get(i)).isTrue(); + for (int i = 5; i < 7; i++) { + assertThat(first.get(i)).isTrue(); + } + for (int i = 10; i < 15; i++) { + assertThat(first.get(i)).isTrue(); + } } @Test From adc586c566c65f256bb9d84c25416f01c4d73e9c Mon Sep 17 00:00:00 2001 From: helga_sh Date: Tue, 21 Jul 2020 16:24:31 +0300 Subject: [PATCH 075/155] CNN example with Deeplearning4j in Java --- deeplearning4j/pom.xml | 10 ++ .../deeplearning4j/cnn/CnnExample.java | 21 +++ .../cnn/domain/network/CnnModel.java | 120 ++++++++++++++++++ .../domain/network/CnnModelProperties.java | 13 ++ .../service/dataset/CifarDataSetService.java | 46 +++++++ .../cnn/service/dataset/IDataSetService.java | 16 +++ 6 files changed, 226 insertions(+) create mode 100644 deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java create mode 100644 deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java create mode 100644 deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java create mode 100644 deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java create mode 100644 deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index c8fa18cbd4..d88c877aa4 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -37,6 +37,16 @@ deeplearning4j-nn ${dl4j.version} + + org.slf4j + slf4j-api + 1.7.5 + + + org.slf4j + slf4j-log4j12 + 1.7.5 + org.datavec diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java new file mode 100644 index 0000000000..2e2d4392b8 --- /dev/null +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java @@ -0,0 +1,21 @@ +package com.baeldung.deeplearning4j.cnn; + + +import com.baeldung.deeplearning4j.cnn.domain.network.CnnModel; +import com.baeldung.deeplearning4j.cnn.domain.network.CnnModelProperties; +import com.baeldung.deeplearning4j.cnn.service.dataset.CifarDataSetService; +import lombok.extern.slf4j.Slf4j; +import org.deeplearning4j.eval.Evaluation; + +@Slf4j +public class CnnExample { + + public static void main(String... args) { + CnnModel network = new CnnModel(new CifarDataSetService(), new CnnModelProperties()); + + network.train(); + Evaluation evaluation = network.evaluate(); + + log.info(evaluation.stats()); + } +} diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java new file mode 100644 index 0000000000..037d14529c --- /dev/null +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java @@ -0,0 +1,120 @@ +package com.baeldung.deeplearning4j.cnn.domain.network; + +import com.baeldung.deeplearning4j.cnn.service.dataset.IDataSetService; +import lombok.extern.slf4j.Slf4j; +import org.deeplearning4j.eval.Evaluation; +import org.deeplearning4j.nn.api.OptimizationAlgorithm; +import org.deeplearning4j.nn.conf.MultiLayerConfiguration; +import org.deeplearning4j.nn.conf.NeuralNetConfiguration; +import org.deeplearning4j.nn.conf.layers.ConvolutionLayer; +import org.deeplearning4j.nn.conf.layers.OutputLayer; +import org.deeplearning4j.nn.conf.layers.SubsamplingLayer; +import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; +import org.deeplearning4j.nn.weights.WeightInit; +import org.nd4j.linalg.activations.Activation; +import org.nd4j.linalg.lossfunctions.LossFunctions; + +import java.util.stream.IntStream; + +@Slf4j +public class CnnModel { + + private final IDataSetService dataSetService; + + private MultiLayerNetwork network; + + private final CnnModelProperties properties; + + public CnnModel(IDataSetService dataSetService, CnnModelProperties properties) { + + this.dataSetService = dataSetService; + this.properties = properties; + + MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder() + .seed(1611) + .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) + .learningRate(properties.getLearningRate()) + .regularization(true) + .updater(properties.getOptimizer()) + .list() + .layer(0, conv5x5()) + .layer(1, pooling2x2Stride2()) + .layer(2, conv3x3Stride1Padding2()) + .layer(3, pooling2x2Stride1()) + .layer(4, conv3x3Stride1Padding1()) + .layer(5, pooling2x2Stride1()) + .layer(6, dense()) + .pretrain(false) + .backprop(true) + .setInputType(dataSetService.inputType()) + .build(); + + network = new MultiLayerNetwork(configuration); + } + + public void train() { + network.init(); + int epochsNum = properties.getEpochsNum(); + IntStream.range(1, epochsNum + 1).forEach(epoch -> { + log.info(String.format("Epoch %d?%d", epoch, epochsNum)); + network.fit(dataSetService.trainIterator()); + }); + } + + public Evaluation evaluate() { + return network.evaluate(dataSetService.testIterator()); + } + + private ConvolutionLayer conv5x5() { + return new ConvolutionLayer.Builder(5, 5) + .nIn(3) + .nOut(16) + .stride(1, 1) + .padding(1, 1) + .weightInit(WeightInit.XAVIER_UNIFORM) + .activation(Activation.RELU) + .build(); + } + + private SubsamplingLayer pooling2x2Stride2() { + return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) + .kernelSize(2, 2) + .stride(2, 2) + .build(); + } + + private ConvolutionLayer conv3x3Stride1Padding2() { + return new ConvolutionLayer.Builder(3, 3) + .nOut(32) + .stride(1, 1) + .padding(2, 2) + .weightInit(WeightInit.XAVIER_UNIFORM) + .activation(Activation.RELU) + .build(); + } + + private SubsamplingLayer pooling2x2Stride1() { + return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) + .kernelSize(2,2) + .stride(1, 1) + .build(); + } + + private ConvolutionLayer conv3x3Stride1Padding1() { + return new ConvolutionLayer.Builder(3, 3) + .nOut(64) + .stride(1, 1) + .padding(1, 1) + .weightInit(WeightInit.XAVIER_UNIFORM) + .activation(Activation.RELU) + .build(); + } + + private OutputLayer dense() { + return new OutputLayer.Builder(LossFunctions.LossFunction.MEAN_SQUARED_LOGARITHMIC_ERROR) + .activation(Activation.SOFTMAX) + .weightInit(WeightInit.XAVIER_UNIFORM) + .nOut(dataSetService.labels().size() - 1) + .build(); + } +} diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java new file mode 100644 index 0000000000..7ea3a71363 --- /dev/null +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java @@ -0,0 +1,13 @@ +package com.baeldung.deeplearning4j.cnn.domain.network; + +import lombok.Value; +import org.deeplearning4j.nn.conf.Updater; + +@Value +public class CnnModelProperties { + private final int epochsNum = 512; + + private final double learningRate = 0.001; + + private final Updater optimizer = Updater.ADAM; +} diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java new file mode 100644 index 0000000000..cb69d0c818 --- /dev/null +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java @@ -0,0 +1,46 @@ +package com.baeldung.deeplearning4j.cnn.service.dataset; + +import lombok.Getter; +import org.deeplearning4j.datasets.iterator.impl.CifarDataSetIterator; +import org.deeplearning4j.nn.conf.inputs.InputType; +import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; + +import java.util.List; + +@Getter +public class CifarDataSetService implements IDataSetService { + + private CifarDataSetIterator trainIterator; + private CifarDataSetIterator testIterator; + + private final InputType inputType = InputType.convolutional(32,32,3); + private final int trainImagesNum = 512; + private final int testImagesNum = 128; + private final int trainBatch = 16; + private final int testBatch = 8; + + public CifarDataSetService() { + trainIterator = new CifarDataSetIterator(trainBatch, trainImagesNum, true); + testIterator = new CifarDataSetIterator(testBatch, testImagesNum, false); + } + + @Override + public DataSetIterator trainIterator() { + return trainIterator; + } + + @Override + public DataSetIterator testIterator() { + return testIterator; + } + + @Override + public InputType inputType() { + return inputType; + } + + @Override + public List labels() { + return trainIterator.getLabels(); + } +} diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java new file mode 100644 index 0000000000..c27e566076 --- /dev/null +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java @@ -0,0 +1,16 @@ +package com.baeldung.deeplearning4j.cnn.service.dataset; + +import org.deeplearning4j.nn.conf.inputs.InputType; +import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; + +import java.util.List; + +public interface IDataSetService { + DataSetIterator trainIterator(); + + DataSetIterator testIterator(); + + InputType inputType(); + + List labels(); +} From 51f1fc9b1e07d5bd342b583b750b66bcabf13838 Mon Sep 17 00:00:00 2001 From: helga_sh Date: Thu, 23 Jul 2020 16:17:04 +0300 Subject: [PATCH 076/155] CNN example with Deeplearning4j in Java: refactor --- deeplearning4j/pom.xml | 5 +++-- .../dataset => }/CifarDataSetService.java | 15 ++++++------- .../deeplearning4j/cnn/CnnExample.java | 5 +---- .../cnn/{domain/network => }/CnnModel.java | 21 +++++++++---------- .../network => }/CnnModelProperties.java | 4 ++-- .../dataset => }/IDataSetService.java | 4 ++-- 6 files changed, 26 insertions(+), 28 deletions(-) rename deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/{service/dataset => }/CifarDataSetService.java (79%) rename deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/{domain/network => }/CnnModel.java (86%) rename deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/{domain/network => }/CnnModelProperties.java (70%) rename deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/{service/dataset => }/IDataSetService.java (74%) diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index d88c877aa4..e1e4998c98 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -40,12 +40,12 @@ org.slf4j slf4j-api - 1.7.5 + ${sl4j.version} org.slf4j slf4j-log4j12 - 1.7.5 + ${sl4j.version} @@ -63,6 +63,7 @@ 0.9.1 4.3.5 + 1.7.5 diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CifarDataSetService.java similarity index 79% rename from deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java rename to deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CifarDataSetService.java index cb69d0c818..70348a6d9e 100644 --- a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/CifarDataSetService.java +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CifarDataSetService.java @@ -1,4 +1,4 @@ -package com.baeldung.deeplearning4j.cnn.service.dataset; +package com.baeldung.deeplearning4j.cnn; import lombok.Getter; import org.deeplearning4j.datasets.iterator.impl.CifarDataSetIterator; @@ -8,18 +8,19 @@ import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import java.util.List; @Getter -public class CifarDataSetService implements IDataSetService { +class CifarDataSetService implements IDataSetService { - private CifarDataSetIterator trainIterator; - private CifarDataSetIterator testIterator; - - private final InputType inputType = InputType.convolutional(32,32,3); + private final InputType inputType = InputType.convolutional(32, 32, 3); private final int trainImagesNum = 512; private final int testImagesNum = 128; private final int trainBatch = 16; private final int testBatch = 8; - public CifarDataSetService() { + private final CifarDataSetIterator trainIterator; + + private final CifarDataSetIterator testIterator; + + CifarDataSetService() { trainIterator = new CifarDataSetIterator(trainBatch, trainImagesNum, true); testIterator = new CifarDataSetIterator(testBatch, testImagesNum, false); } diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java index 2e2d4392b8..224062c388 100644 --- a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnExample.java @@ -1,14 +1,11 @@ package com.baeldung.deeplearning4j.cnn; -import com.baeldung.deeplearning4j.cnn.domain.network.CnnModel; -import com.baeldung.deeplearning4j.cnn.domain.network.CnnModelProperties; -import com.baeldung.deeplearning4j.cnn.service.dataset.CifarDataSetService; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.eval.Evaluation; @Slf4j -public class CnnExample { +class CnnExample { public static void main(String... args) { CnnModel network = new CnnModel(new CifarDataSetService(), new CnnModelProperties()); diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java similarity index 86% rename from deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java rename to deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java index 037d14529c..bd87709c0e 100644 --- a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModel.java +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java @@ -1,6 +1,5 @@ -package com.baeldung.deeplearning4j.cnn.domain.network; +package com.baeldung.deeplearning4j.cnn; -import com.baeldung.deeplearning4j.cnn.service.dataset.IDataSetService; import lombok.extern.slf4j.Slf4j; import org.deeplearning4j.eval.Evaluation; import org.deeplearning4j.nn.api.OptimizationAlgorithm; @@ -17,15 +16,15 @@ import org.nd4j.linalg.lossfunctions.LossFunctions; import java.util.stream.IntStream; @Slf4j -public class CnnModel { +class CnnModel { private final IDataSetService dataSetService; - private MultiLayerNetwork network; + private final MultiLayerNetwork network; private final CnnModelProperties properties; - public CnnModel(IDataSetService dataSetService, CnnModelProperties properties) { + CnnModel(IDataSetService dataSetService, CnnModelProperties properties) { this.dataSetService = dataSetService; this.properties = properties; @@ -52,17 +51,17 @@ public class CnnModel { network = new MultiLayerNetwork(configuration); } - public void train() { + void train() { network.init(); int epochsNum = properties.getEpochsNum(); IntStream.range(1, epochsNum + 1).forEach(epoch -> { - log.info(String.format("Epoch %d?%d", epoch, epochsNum)); + log.info("Epoch {} / {}", epoch, epochsNum); network.fit(dataSetService.trainIterator()); }); } - public Evaluation evaluate() { - return network.evaluate(dataSetService.testIterator()); + Evaluation evaluate() { + return network.evaluate(dataSetService.testIterator()); } private ConvolutionLayer conv5x5() { @@ -84,7 +83,7 @@ public class CnnModel { } private ConvolutionLayer conv3x3Stride1Padding2() { - return new ConvolutionLayer.Builder(3, 3) + return new ConvolutionLayer.Builder(3, 3) .nOut(32) .stride(1, 1) .padding(2, 2) @@ -95,7 +94,7 @@ public class CnnModel { private SubsamplingLayer pooling2x2Stride1() { return new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX) - .kernelSize(2,2) + .kernelSize(2, 2) .stride(1, 1) .build(); } diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModelProperties.java similarity index 70% rename from deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java rename to deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModelProperties.java index 7ea3a71363..d010d789c8 100644 --- a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/domain/network/CnnModelProperties.java +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModelProperties.java @@ -1,10 +1,10 @@ -package com.baeldung.deeplearning4j.cnn.domain.network; +package com.baeldung.deeplearning4j.cnn; import lombok.Value; import org.deeplearning4j.nn.conf.Updater; @Value -public class CnnModelProperties { +class CnnModelProperties { private final int epochsNum = 512; private final double learningRate = 0.001; diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/IDataSetService.java similarity index 74% rename from deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java rename to deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/IDataSetService.java index c27e566076..ea88bf550c 100644 --- a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/service/dataset/IDataSetService.java +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/IDataSetService.java @@ -1,11 +1,11 @@ -package com.baeldung.deeplearning4j.cnn.service.dataset; +package com.baeldung.deeplearning4j.cnn; import org.deeplearning4j.nn.conf.inputs.InputType; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import java.util.List; -public interface IDataSetService { +interface IDataSetService { DataSetIterator trainIterator(); DataSetIterator testIterator(); From 06a10e83536d815e2775944a11780051a8d2dcaf Mon Sep 17 00:00:00 2001 From: helga_sh Date: Thu, 23 Jul 2020 17:33:06 +0300 Subject: [PATCH 077/155] CNN example with Deeplearning4j in Java: add missing letter in pom --- deeplearning4j/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index e1e4998c98..8ec335b184 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -63,7 +63,7 @@ 0.9.1 4.3.5 - 1.7.5 + 1.7.5 From c67658322b281f5eff5ff9b7556f0119df607b20 Mon Sep 17 00:00:00 2001 From: helga_sh Date: Thu, 23 Jul 2020 17:33:31 +0300 Subject: [PATCH 078/155] CNN example with Deeplearning4j in Java: add missing letter in pom --- deeplearning4j/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index 8ec335b184..af65aa7e03 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -40,12 +40,12 @@ org.slf4j slf4j-api - ${sl4j.version} + ${slf4j.version} org.slf4j slf4j-log4j12 - ${sl4j.version} + ${slf4j.version} From 2127c7935452ca7556b65f913c598bcf36513f24 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Thu, 23 Jul 2020 19:00:08 +0200 Subject: [PATCH 079/155] BAEL-4289 --- .../baeldung/screenshot/ScreenshotTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java new file mode 100644 index 0000000000..3df31897e1 --- /dev/null +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java @@ -0,0 +1,54 @@ +import javax.imageio.ImageIO; +import java.awt.Component; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.image.BufferedImage; +import java.io.File; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class ScreenshotTest { + + @Test + public void takeScreenshotOfMainScreen() throws Exception { + Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); + BufferedImage capture = new Robot().createScreenCapture(screenRect); + File imageFile = new File("single-screen.bmp"); + ImageIO.write(capture, "bmp", imageFile); + assertTrue(imageFile.exists()); + imageFile.delete(); + } + + @Test + public void takeScreenshotOfAllScreens() throws Exception { + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + GraphicsDevice[] screens = ge.getScreenDevices(); + Rectangle allScreenBounds = new Rectangle(); + for (GraphicsDevice screen : screens) { + Rectangle screenBounds = screen.getDefaultConfiguration().getBounds(); + allScreenBounds.width += screenBounds.width; + allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height); + } + BufferedImage capture = new Robot().createScreenCapture(allScreenBounds); + File imageFile = new File("all-screens.bmp"); + ImageIO.write(capture, "bmp", imageFile); + assertTrue(imageFile.exists()); + imageFile.delete(); + } + + @Test + public void makeScreenshot(Component component) throws Exception { + Rectangle componentRect = component.getBounds(); + BufferedImage bufferedImage = new BufferedImage(componentRect.width, componentRect.height, BufferedImage.TYPE_INT_ARGB); + component.paint(bufferedImage.getGraphics()); + File imageFile = new File("component-screenshot.bmp"); + ImageIO.write(bufferedImage, "bmp", imageFile); + assertTrue(imageFile.exists()); + imageFile.delete(); + } + +} \ No newline at end of file From 9c0eba409e86db1e7b609bb53db075b914cd5ec6 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Thu, 23 Jul 2020 19:29:59 +0200 Subject: [PATCH 080/155] BAEL-4405 Probability in Java --- .../probability/MaleHeightGenerator.java | 17 +++++++++++++ .../baeldung/probability/RandomInvoker.java | 19 +++++++++++++++ .../probability/RandomInvokerUnitTest.java | 24 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 java-numbers-3/src/main/java/com/baeldung/probability/MaleHeightGenerator.java create mode 100644 java-numbers-3/src/main/java/com/baeldung/probability/RandomInvoker.java create mode 100644 java-numbers-3/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java diff --git a/java-numbers-3/src/main/java/com/baeldung/probability/MaleHeightGenerator.java b/java-numbers-3/src/main/java/com/baeldung/probability/MaleHeightGenerator.java new file mode 100644 index 0000000000..ed3fb8a578 --- /dev/null +++ b/java-numbers-3/src/main/java/com/baeldung/probability/MaleHeightGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.probability; + +import org.apache.commons.math3.distribution.NormalDistribution; + +public class MaleHeightGenerator { + private static final double MEAN_HEIGHT = 176.02; + private static final double STANDARD_DEVIATION = 7.11; + private static NormalDistribution distribution = new NormalDistribution(MEAN_HEIGHT, STANDARD_DEVIATION); + + public static double generateNormalHeight() { + return distribution.sample(); + } + + public static double probabilityOfHeightBetween(double heightLowerExclusive, double heightUpperInclusive) { + return distribution.probability(heightLowerExclusive, heightUpperInclusive); + } +} diff --git a/java-numbers-3/src/main/java/com/baeldung/probability/RandomInvoker.java b/java-numbers-3/src/main/java/com/baeldung/probability/RandomInvoker.java new file mode 100644 index 0000000000..30be5725ab --- /dev/null +++ b/java-numbers-3/src/main/java/com/baeldung/probability/RandomInvoker.java @@ -0,0 +1,19 @@ +package com.baeldung.probability; + +import io.vavr.Lazy; + +import java.util.SplittableRandom; +import java.util.function.Supplier; + +public class RandomInvoker { + private final Lazy random = Lazy.of(SplittableRandom::new); + + public T withProbability(Supplier supplier1, Supplier supplier2, int probability) { + SplittableRandom random = this.random.get(); + if (random.nextInt(1, 101) <= probability) { + return supplier1.get(); + } else { + return supplier2.get(); + } + } +} diff --git a/java-numbers-3/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java b/java-numbers-3/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java new file mode 100644 index 0000000000..b08c086e30 --- /dev/null +++ b/java-numbers-3/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.probability; + +import org.assertj.core.data.Offset; +import org.junit.Test; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RandomInvokerUnitTest { + @Test + public void givenProbability_whenInvoked_invokeWithProbability() { + RandomInvoker randomInvoker = new RandomInvoker(); + + int numberOfSamples = 1_000_000; + int probability = 10; + int howManyTimesInvoked = Stream.generate(() -> randomInvoker.withProbability(() -> 1, () -> 0, probability)) + .limit(numberOfSamples) + .mapToInt(e -> e).sum(); + int monteCarloProbability = (howManyTimesInvoked * 100) / numberOfSamples; + + assertThat(monteCarloProbability).isCloseTo(probability, Offset.offset(1)); + } +} From c4770ac40f83ee773426004fd8a4168b57a37aa5 Mon Sep 17 00:00:00 2001 From: karan Date: Fri, 24 Jul 2020 01:08:45 -0400 Subject: [PATCH 081/155] add another defaultpathvariable method --- .../pathvariable/PathVariableAnnotationController.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java index 624ba2d105..37e104f354 100644 --- a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java @@ -66,6 +66,16 @@ public class PathVariableAnnotationController { } } + @GetMapping(value = { "/api/defaultemployeeswithoptional", "/api/defaultemployeeswithoptional/{id}" }) + @ResponseBody + public String getDefaultEmployeesByIdWithOptional(@PathVariable Optional id) { + if (id.isPresent()) { + return "ID: " + id.get(); + } else { + return "ID: Default Employee"; + } + } + @GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" }) @ResponseBody public String getEmployeesByIdWithMap(@PathVariable Map pathVarsMap) { From 0a2f6a4615f6f751942e1f8a6da477c02a42316c Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Fri, 24 Jul 2020 20:13:23 +0530 Subject: [PATCH 082/155] Added code to set a field using Reflection. --- .../reflection/set/fields/Person.java | 87 +++++++++ .../SetFieldsUsingReflectionUnitTest.java | 182 ++++++++++++++++++ 2 files changed, 269 insertions(+) create mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java create mode 100644 core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java new file mode 100644 index 0000000000..6bdfc58d78 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java @@ -0,0 +1,87 @@ +package com.baeldung.reflection.set.fields; + +public class Person { + + private String name; + private byte age; + private short uidNumber; + private int pinCode; + private long contactNumber; + private float height; + private double weight; + private char gender; + private boolean active; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public byte getAge() { + return age; + } + + public void setAge(byte age) { + this.age = age; + } + + public short getUidNumber() { + return uidNumber; + } + + public void setUidNumber(short uidNumber) { + this.uidNumber = uidNumber; + } + + public int getPinCode() { + return pinCode; + } + + public void setPinCode(int pinCode) { + this.pinCode = pinCode; + } + + public long getContactNumber() { + return contactNumber; + } + + public void setContactNumber(long contactNumber) { + this.contactNumber = contactNumber; + } + + public float getHeight() { + return height; + } + + public void setHeight(float height) { + this.height = height; + } + + public double getWeight() { + return weight; + } + + public void setWeight(double weight) { + this.weight = weight; + } + + public char getGender() { + return gender; + } + + public void setGender(char gender) { + this.gender = gender; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + +} diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java new file mode 100644 index 0000000000..18a378cf07 --- /dev/null +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java @@ -0,0 +1,182 @@ +package com.baeldung.reflection.set.fields; + +import java.lang.reflect.Field; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class SetFieldsUsingReflectionUnitTest { + + @Test + public void whenSetIntegerFields_thenSuccess() throws Exception { + Person person = new Person(); + + Field ageField = person.getClass() + .getDeclaredField("age"); + ageField.setAccessible(true); + + byte age = 26; + ageField.setByte(person, age); + Assertions.assertEquals(26, person.getAge()); + + Field uidNumberField = person.getClass() + .getDeclaredField("uidNumber"); + uidNumberField.setAccessible(true); + + short uidNumber = 5555; + uidNumberField.setShort(person, uidNumber); + Assertions.assertEquals(5555, person.getUidNumber()); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + int pinCode = 411057; + pinCodeField.setInt(person, pinCode); + Assertions.assertEquals(411057, person.getPinCode()); + + Field contactNumberField = person.getClass() + .getDeclaredField("contactNumber"); + contactNumberField.setAccessible(true); + + long contactNumber = 123456789L; + contactNumberField.setLong(person, contactNumber); + Assertions.assertEquals(123456789L, person.getContactNumber()); + + } + + @Test + public void whenDoUnboxing_thenSuccess() throws Exception { + Person person = new Person(); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + Integer pinCode = 411057; + pinCodeField.setInt(person, pinCode); + Assertions.assertEquals(411057, person.getPinCode()); + } + + @Test + public void whenDoNarrowing_thenSuccess() throws Exception { + Person person = new Person(); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + Short pinCode = 4110; + pinCodeField.setInt(person, pinCode); + Assertions.assertEquals(4110, person.getPinCode()); + } + + @Test + public void whenSetFloatingTypeFields_thenSuccess() throws Exception { + Person person = new Person(); + + Field heightField = person.getClass() + .getDeclaredField("height"); + heightField.setAccessible(true); + + float height = 6.1242f; + heightField.setFloat(person, height); + Assertions.assertEquals(6.1242f, person.getHeight()); + + Field weightField = person.getClass() + .getDeclaredField("weight"); + weightField.setAccessible(true); + + double weight = 75.2564; + weightField.setDouble(person, weight); + Assertions.assertEquals(75.2564, person.getWeight()); + } + + @Test + public void whenSetCharacterFields_thenSuccess() throws Exception { + Person person = new Person(); + + Field genderField = person.getClass() + .getDeclaredField("gender"); + genderField.setAccessible(true); + + char gender = 'M'; + genderField.setChar(person, gender); + Assertions.assertEquals('M', person.getGender()); + } + + @Test + public void whenSetBooleanFields_thenSuccess() throws Exception { + Person person = new Person(); + + Field activeField = person.getClass() + .getDeclaredField("active"); + activeField.setAccessible(true); + + boolean active = true; + activeField.setBoolean(person, active); + Assertions.assertTrue(person.isActive()); + } + + @Test + public void whenSetObjectFields_thenSuccess() throws Exception { + Person person = new Person(); + + Field nameField = person.getClass() + .getDeclaredField("name"); + nameField.setAccessible(true); + + String name = "Umang Budhwar"; + nameField.set(person, name); + Assertions.assertEquals("Umang Budhwar", person.getName()); + } + + @Test + public void givenInt_whenSetStringField_thenIllegalArgumentException() throws Exception { + Person person = new Person(); + Field nameField = person.getClass() + .getDeclaredField("name"); + nameField.setAccessible(true); + + Assertions.assertThrows(IllegalArgumentException.class, () -> nameField.setInt(person, 26)); + } + + @Test + public void givenInt_whenSetLongField_thenIllegalArgumentException() throws Exception { + Person person = new Person(); + + Field pinCodeField = person.getClass() + .getDeclaredField("pinCode"); + pinCodeField.setAccessible(true); + + long pinCode = 411057L; + + Assertions.assertThrows(IllegalArgumentException.class, () -> pinCodeField.setLong(person, pinCode)); + } + + @Test + public void whenFieldNotSetAccessible_thenIllegalAccessException() throws Exception { + Person person = new Person(); + Field nameField = person.getClass() + .getDeclaredField("name"); + + Assertions.assertThrows(IllegalAccessException.class, () -> nameField.set(person, "Umang Budhwar")); + } + + @Test + public void whenAccessingWrongProperty_thenNoSuchFieldException() throws Exception { + Person person = new Person(); + + Assertions.assertThrows(NoSuchFieldException.class, () -> person.getClass() + .getDeclaredField("firstName")); + } + + @Test + public void whenAccessingNullProperty_thenNullPointerException() throws Exception { + Person person = new Person(); + + Assertions.assertThrows(NullPointerException.class, () -> person.getClass() + .getDeclaredField(null)); + } + +} From d52bb494e113a545faaf657d81531ae6c9fa0f7e Mon Sep 17 00:00:00 2001 From: Jordan Simpson Date: Sat, 25 Jul 2020 11:41:20 -0500 Subject: [PATCH 083/155] Added project hierarchy to exemplify the tag. --- maven-modules/optional-dependencies/README.md | 3 +++ .../main-project/pom.xml | 18 ++++++++++++++++++ .../optional-project/pom.xml | 10 ++++++++++ maven-modules/optional-dependencies/pom.xml | 18 ++++++++++++++++++ .../project-with-optionals/pom.xml | 19 +++++++++++++++++++ maven-modules/pom.xml | 1 + 6 files changed, 69 insertions(+) create mode 100644 maven-modules/optional-dependencies/README.md create mode 100644 maven-modules/optional-dependencies/main-project/pom.xml create mode 100644 maven-modules/optional-dependencies/optional-project/pom.xml create mode 100644 maven-modules/optional-dependencies/pom.xml create mode 100644 maven-modules/optional-dependencies/project-with-optionals/pom.xml diff --git a/maven-modules/optional-dependencies/README.md b/maven-modules/optional-dependencies/README.md new file mode 100644 index 0000000000..6b4d3e7647 --- /dev/null +++ b/maven-modules/optional-dependencies/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- Optional Dependency in Maven \ No newline at end of file diff --git a/maven-modules/optional-dependencies/main-project/pom.xml b/maven-modules/optional-dependencies/main-project/pom.xml new file mode 100644 index 0000000000..6a42683779 --- /dev/null +++ b/maven-modules/optional-dependencies/main-project/pom.xml @@ -0,0 +1,18 @@ + + + 4.0.0 + com.baeldung + main-project + 0.0.1-SNAPSHOT + pom + + + + com.baeldung + project-with-optionals + 0.0.1-SNAPSHOT + + + \ No newline at end of file diff --git a/maven-modules/optional-dependencies/optional-project/pom.xml b/maven-modules/optional-dependencies/optional-project/pom.xml new file mode 100644 index 0000000000..9ad4376c8d --- /dev/null +++ b/maven-modules/optional-dependencies/optional-project/pom.xml @@ -0,0 +1,10 @@ + + + 4.0.0 + com.baeldung + optional-project + 0.0.1-SNAPSHOT + pom + \ No newline at end of file diff --git a/maven-modules/optional-dependencies/pom.xml b/maven-modules/optional-dependencies/pom.xml new file mode 100644 index 0000000000..c1bfc6fb59 --- /dev/null +++ b/maven-modules/optional-dependencies/pom.xml @@ -0,0 +1,18 @@ + + + + maven-modules + com.baeldung + 0.0.1-SNAPSHOT + + 4.0.0 + + optional-dependencies + + optional-project + project-with-optionals + main-project + + \ No newline at end of file diff --git a/maven-modules/optional-dependencies/project-with-optionals/pom.xml b/maven-modules/optional-dependencies/project-with-optionals/pom.xml new file mode 100644 index 0000000000..6a14f3260d --- /dev/null +++ b/maven-modules/optional-dependencies/project-with-optionals/pom.xml @@ -0,0 +1,19 @@ + + + 4.0.0 + com.baeldung + project-with-optionals + 0.0.1-SNAPSHOT + pom + + + + com.baeldung + optional-project + 0.0.1-SNAPSHOT + true + + + \ No newline at end of file diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index 528f44bddc..86a7d5756c 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -26,6 +26,7 @@ maven-properties versions-maven-plugin version-collision + optional-dependencies From e3999c9112a8aa46173aa7c09ea72626a44f1113 Mon Sep 17 00:00:00 2001 From: mdhtr Date: Mon, 20 Jul 2020 21:14:49 +0200 Subject: [PATCH 084/155] Changes based on editor review - extract Person classes from test classes - shorten test name of one test - fix one warning --- .../JacksonDeserializationUnitTest.java | 4 ++-- .../HydraJsonldSerializationUnitTest.java | 12 ------------ .../serialization/hydrajsonld/Person.java | 15 +++++++++++++++ .../JacksonJsonLdSerializationUnitTest.java | 17 ----------------- .../serialization/jacksonjsonld/Person.java | 19 +++++++++++++++++++ 5 files changed, 36 insertions(+), 31 deletions(-) create mode 100644 json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java create mode 100644 json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java diff --git a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java index 35a2613957..df09a98f76 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java @@ -16,11 +16,11 @@ import com.github.jsonldjava.utils.JsonUtils; public class JacksonDeserializationUnitTest { @Test - void givenAJsonLdObject_whenCompactIsUsedWithEmptyContext_thenItCanBeDeserializedIntoAJacksonAnnotatedJavaObject() throws IOException { + void givenAJsonLdObject_whenCompactIsUsedWithEmptyContext_thenItCanBeDeserializedWithJackson() throws IOException { String inputJsonLd = "{\"@context\":{\"@vocab\":\"http://schema.org/\",\"knows\":{\"@type\":\"@id\"}},\"@type\":\"Person\",\"@id\":\"http://example.com/person/1234\",\"name\":\"Example Name\",\"knows\":\"http://example.com/person/2345\"}"; Object jsonObject = JsonUtils.fromString(inputJsonLd); - Object compact = JsonLdProcessor.compact(jsonObject, new HashMap(), new JsonLdOptions()); + Object compact = JsonLdProcessor.compact(jsonObject, new HashMap<>(), new JsonLdOptions()); String compactContent = JsonUtils.toString(compact); assertEquals("{\"@id\":\"http://example.com/person/1234\",\"@type\":\"http://schema.org/Person\",\"http://schema.org/knows\":{\"@id\":\"http://example.com/person/2345\"},\"http://schema.org/name\":\"Example Name\"}", compactContent); diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java index e5d1e35236..308987a0bd 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonSerializer; @@ -15,20 +14,9 @@ import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.BeanSerializerModifier; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; -import de.escalon.hypermedia.hydra.mapping.Expose; -import de.escalon.hypermedia.hydra.mapping.Vocab; import de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer; public class HydraJsonldSerializationUnitTest { - @Vocab("http://example.com/vocab/") - @Expose("person") - static class Person { - @JsonProperty("@id") - public String id; - @Expose("fullName") - public String name; - } - @Test void givenAHydraJsonldAnnotatedObject_whenJacksonHydraSerializerIsUsed_thenAJsonLdDocumentIsGenerated() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java new file mode 100644 index 0000000000..87587d02ac --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java @@ -0,0 +1,15 @@ +package com.baeldung.jsonld.serialization.hydrajsonld; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import de.escalon.hypermedia.hydra.mapping.Expose; +import de.escalon.hypermedia.hydra.mapping.Vocab; + +@Vocab("http://example.com/vocab/") +@Expose("person") +public class Person { + @JsonProperty("@id") + public String id; + @Expose("fullName") + public String name; +} diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java index b539c73608..07e44b4981 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java @@ -8,25 +8,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import ioinformarics.oss.jackson.module.jsonld.JsonldModule; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldId; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldLink; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldNamespace; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldProperty; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldResource; -import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType; public class JacksonJsonLdSerializationUnitTest { - @JsonldResource - @JsonldNamespace(name = "s", uri = "http://schema.org/") - @JsonldType("s:Person") - @JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345") - static class Person { - @JsonldId - public String id = "http://example.com/person/1234"; - @JsonldProperty("s:name") - public String name = "Example Name"; - } - @Test void givenAJacksonJsonldAnnotatedObject_whenJsonldModuleIsUsed_thenAJsonLdDocumentIsGenerated() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java new file mode 100644 index 0000000000..d0c9e4f111 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java @@ -0,0 +1,19 @@ +package com.baeldung.jsonld.serialization.jacksonjsonld; + +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldId; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldLink; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldNamespace; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldProperty; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldResource; +import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType; + +@JsonldResource +@JsonldNamespace(name = "s", uri = "http://schema.org/") +@JsonldType("s:Person") +@JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345") +public class Person { + @JsonldId + public String id = "http://example.com/person/1234"; + @JsonldProperty("s:name") + public String name = "Example Name"; +} From f83f670bf757954f82f5ee688a025d9302656242 Mon Sep 17 00:00:00 2001 From: mdhtr Date: Sun, 26 Jul 2020 09:44:17 +0200 Subject: [PATCH 085/155] Format inline JSON objects by hand --- .../JacksonDeserializationUnitTest.java | 18 ++++++++++++++++-- .../HydraJsonldSerializationUnitTest.java | 10 +++++++++- .../JacksonJsonLdSerializationUnitTest.java | 14 +++++++++++--- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java index df09a98f76..9c6b6f976a 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java @@ -17,13 +17,27 @@ public class JacksonDeserializationUnitTest { @Test void givenAJsonLdObject_whenCompactIsUsedWithEmptyContext_thenItCanBeDeserializedWithJackson() throws IOException { - String inputJsonLd = "{\"@context\":{\"@vocab\":\"http://schema.org/\",\"knows\":{\"@type\":\"@id\"}},\"@type\":\"Person\",\"@id\":\"http://example.com/person/1234\",\"name\":\"Example Name\",\"knows\":\"http://example.com/person/2345\"}"; + String inputJsonLd = "{" + + "\"@context\":{" + + "\"@vocab\":\"http://schema.org/\"," + + "\"knows\":{\"@type\":\"@id\"}" + + "}," + + "\"@type\":\"Person\"," + + "\"@id\":\"http://example.com/person/1234\"," + + "\"name\":\"Example Name\"," + + "\"knows\":\"http://example.com/person/2345\"" + + "}"; Object jsonObject = JsonUtils.fromString(inputJsonLd); Object compact = JsonLdProcessor.compact(jsonObject, new HashMap<>(), new JsonLdOptions()); String compactContent = JsonUtils.toString(compact); - assertEquals("{\"@id\":\"http://example.com/person/1234\",\"@type\":\"http://schema.org/Person\",\"http://schema.org/knows\":{\"@id\":\"http://example.com/person/2345\"},\"http://schema.org/name\":\"Example Name\"}", compactContent); + assertEquals("{" + + "\"@id\":\"http://example.com/person/1234\"," + + "\"@type\":\"http://schema.org/Person\"," + + "\"http://schema.org/knows\":{\"@id\":\"http://example.com/person/2345\"}," + + "\"http://schema.org/name\":\"Example Name\"" + + "}", compactContent); ObjectMapper objectMapper = new ObjectMapper(); Person person = objectMapper.readValue(compactContent, Person.class); diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java index 308987a0bd..06105d579e 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java @@ -29,7 +29,15 @@ public class HydraJsonldSerializationUnitTest { String personJsonLd = objectMapper.writeValueAsString(person); - assertEquals("{\"@context\":{\"@vocab\":\"http://example.com/vocab/\",\"name\":\"fullName\"},\"@type\":\"person\",\"name\":\"Example Name\",\"@id\":\"http://example.com/person/1234\"}", personJsonLd); + assertEquals("{" + + "\"@context\":{" + + "\"@vocab\":\"http://example.com/vocab/\"," + + "\"name\":\"fullName\"" + + "}," + + "\"@type\":\"person\"," + + "\"name\":\"Example Name\"," + + "\"@id\":\"http://example.com/person/1234\"" + + "}", personJsonLd); } static SimpleModule getJacksonHydraSerializerModule() { diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java index 07e44b4981..cd41989a53 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java @@ -18,8 +18,16 @@ public class JacksonJsonLdSerializationUnitTest { Person person = new Person(); String personJsonLd = objectMapper.writeValueAsString(person); - assertEquals( - "{\"@type\":\"s:Person\",\"@context\":{\"s\":\"http://schema.org/\",\"name\":\"s:name\",\"knows\":{\"@id\":\"s:knows\",\"@type\":\"@id\"}},\"name\":\"Example Name\",\"@id\":\"http://example.com/person/1234\",\"knows\":\"http://example.com/person/2345\"}", - personJsonLd); + assertEquals("{" + + "\"@type\":\"s:Person\"," + + "\"@context\":{" + + "\"s\":\"http://schema.org/\"," + + "\"name\":\"s:name\"," + + "\"knows\":{\"@id\":\"s:knows\",\"@type\":\"@id\"}" + + "}," + + "\"name\":\"Example Name\"," + + "\"@id\":\"http://example.com/person/1234\"," + + "\"knows\":\"http://example.com/person/2345\"" + + "}", personJsonLd); } } From 55d15037c0825efd94e48048a8d1889bdbbf4563 Mon Sep 17 00:00:00 2001 From: developerDiv Date: Sun, 26 Jul 2020 17:08:44 +0100 Subject: [PATCH 086/155] Rename DeliveryPlatform send method to 'deliver' to aid readability and avoiding confusion with EmailService.send method Re-arrange order of mocks and inject mocks Rename argument matcher and captor tests --- .../mockito/argumentcaptor/DeliveryPlatform.java | 2 +- .../mockito/argumentcaptor/EmailService.java | 2 +- .../argumentcaptor/EmailServiceUnitTest.java | 14 +++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java index dbad1e1bcf..6cbaf7b97c 100644 --- a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/DeliveryPlatform.java @@ -2,7 +2,7 @@ package com.baeldung.mockito.argumentcaptor; public interface DeliveryPlatform { - void send(Email email); + void deliver(Email email); String getServiceStatus(); diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java index c368f41d2f..d22feaf8a4 100644 --- a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/argumentcaptor/EmailService.java @@ -15,7 +15,7 @@ public class EmailService { } Email email = new Email(to, subject, body); email.setFormat(format); - platform.send(email); + platform.deliver(email); } public ServiceStatus checkServiceStatus() { diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java index 9d18957b2e..5ed7be7d6e 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/argumentcaptor/EmailServiceUnitTest.java @@ -10,12 +10,12 @@ import static org.junit.Assert.*; @RunWith(MockitoJUnitRunner.class) public class EmailServiceUnitTest { - @InjectMocks - EmailService emailService; - @Mock DeliveryPlatform platform; + @InjectMocks + EmailService emailService; + @Captor ArgumentCaptor emailCaptor; @@ -30,7 +30,7 @@ public class EmailServiceUnitTest { emailService.send(to, subject, body, false); - Mockito.verify(platform).send(emailCaptor.capture()); + Mockito.verify(platform).deliver(emailCaptor.capture()); Email emailCaptorValue = emailCaptor.getValue(); assertEquals(Format.TEXT_ONLY, emailCaptorValue.getFormat()); } @@ -43,7 +43,7 @@ public class EmailServiceUnitTest { emailService.send(to, subject, body, true); - Mockito.verify(platform).send(emailCaptor.capture()); + Mockito.verify(platform).deliver(emailCaptor.capture()); Email value = emailCaptor.getValue(); assertEquals(Format.HTML, value.getFormat()); } @@ -67,7 +67,7 @@ public class EmailServiceUnitTest { } @Test - public void usingArgumentMatcher_whenAuthenticatedWithValidCredentials_expectTrue() { + public void whenUsingArgumentMatcherForValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED); @@ -75,7 +75,7 @@ public class EmailServiceUnitTest { } @Test - public void usingArgumentCaptor_whenAuthenticatedWithValidCredentials_expectTrue() { + public void whenUsingArgumentCaptorForValidCredentials_expectTrue() { Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key"); Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED); From 48ea32d583dd5fd5d45aa60516476c3e2096d300 Mon Sep 17 00:00:00 2001 From: STS Date: Sun, 26 Jul 2020 20:01:42 +0200 Subject: [PATCH 087/155] change test class name, add blank line and swap assert method parameter --- .../baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java index 45314519d4..b3f6949216 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java @@ -25,7 +25,7 @@ class ExcelFormulaUnitTest { } @Test - void givenExcelData_whenSetAndEvaluateFormula() throws IOException { + void givenExcelData_whenSetFormula_thenSuccess() throws IOException { FileInputStream inputStream = new FileInputStream(new File(fileLocation)); XSSFWorkbook wb = new XSSFWorkbook(inputStream); XSSFSheet sheet = wb.getSheetAt(0); @@ -43,7 +43,9 @@ class ExcelFormulaUnitTest { String startCellB = colNameB + 1; String stopCellB = colNameB + (sheet.getLastRowNum() + 1); String sumFormulaForColumnB = String.format("SUM(%s:%s)", startCellB, stopCellB); + double resultValue = excelFormula.setFormula(fileLocation, wb, sumFormulaForColumnA + "-" + sumFormulaForColumnB); - Assert.assertEquals(resultValue, resultColumnA - resultColumnB, 0d); + + Assert.assertEquals(resultColumnA - resultColumnB, resultValue, 0d); } } From 78d44e5a6010aecdb209855f1854ad017b2ac89c Mon Sep 17 00:00:00 2001 From: STS Date: Mon, 27 Jul 2020 10:07:30 +0200 Subject: [PATCH 088/155] change baeldung spell --- .../poi/excel/setformula/SetFormulaTest.xlsx | Bin 1 file changed, 0 insertions(+), 0 deletions(-) rename apache-poi/src/main/resources/com/{bealdung => baeldung}/poi/excel/setformula/SetFormulaTest.xlsx (100%) diff --git a/apache-poi/src/main/resources/com/bealdung/poi/excel/setformula/SetFormulaTest.xlsx b/apache-poi/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx similarity index 100% rename from apache-poi/src/main/resources/com/bealdung/poi/excel/setformula/SetFormulaTest.xlsx rename to apache-poi/src/main/resources/com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx From 8ee84bbc4aa5ad94af7b66315d1776ab9faf28f1 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 27 Jul 2020 22:13:05 +0200 Subject: [PATCH 089/155] JAVA-1650: Get rid of the overriden spring-boot.version property --- spring-5-reactive-security/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-5-reactive-security/pom.xml b/spring-5-reactive-security/pom.xml index 58c993bda5..2024cb5138 100644 --- a/spring-5-reactive-security/pom.xml +++ b/spring-5-reactive-security/pom.xml @@ -128,7 +128,6 @@ 1.0 4.1 3.1.6.RELEASE - 2.2.2.RELEASE From 2a58dcf29d8bf5ae716347d7d879536b747ee6a3 Mon Sep 17 00:00:00 2001 From: Maja Joksovic Date: Tue, 28 Jul 2020 01:33:43 +0200 Subject: [PATCH 090/155] initial commit --- .../baeldung/copyfolder/ApacheCommons.java | 15 +++++ .../java/com/baeldung/copyfolder/CoreOld.java | 38 +++++++++++ .../java/com/baeldung/copyfolder/JavaNio.java | 22 +++++++ .../copyfolder/ApacheCommonsUnitTest.java | 59 +++++++++++++++++ .../baeldung/copyfolder/CoreOldUnitTest.java | 63 +++++++++++++++++++ .../baeldung/copyfolder/JavaNioUnitTest.java | 59 +++++++++++++++++ 6 files changed, 256 insertions(+) create mode 100644 core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java create mode 100644 core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java create mode 100644 core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java new file mode 100644 index 0000000000..67af0594a4 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java @@ -0,0 +1,15 @@ +package com.baeldung.copyfolder; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; + +public class ApacheCommons { + + public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { + File sourceFolder = new File(sourceDirectoryLocation); + File destinationFolder = new File(destinationDirectoryLocation); + FileUtils.copyDirectory(sourceFolder, destinationFolder); + } +} diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java new file mode 100644 index 0000000000..d1a0158db3 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java @@ -0,0 +1,38 @@ +package com.baeldung.copyfolder; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public class CoreOld { + + public static void copyDirectoryJavaUnder7(File source, File destination) throws IOException { + if (source.isDirectory()) { + copyDirectory(source, destination); + } else { + copyFile(source, destination); + } + } + + private static void copyDirectory(File sourceFolder, File destinationFolder) throws IOException { + if (!destinationFolder.exists()) { + destinationFolder.mkdir(); + } + for (String f : sourceFolder.list()) { + copyDirectoryJavaUnder7(new File(sourceFolder, f), new File(destinationFolder, f)); + } + } + + private static void copyFile(File sourceFile, File destinationFile) throws IOException { + try (InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destinationFile)) { + byte[] buf = new byte[1024]; + int length; + while ((length = in.read(buf)) > 0) { + out.write(buf, 0, length); + } + } + } +} diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java new file mode 100644 index 0000000000..368118a943 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java @@ -0,0 +1,22 @@ +package com.baeldung.copyfolder; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class JavaNio { + + public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { + Files.walk(Paths.get(sourceDirectoryLocation)) + .forEach(a -> { + Path b = Paths.get(destinationDirectoryLocation, a.toString() + .substring(sourceDirectoryLocation.length())); + try { + Files.copy(a, b); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } +} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java new file mode 100644 index 0000000000..71e4c52104 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.copyfolder; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ApacheCommonsUnitTest { + + private final String sourceFolderLocation = "src/test/resources/sourceFolder"; + private final String subFolderName = "/childFolder"; + private final String fileName = "/file.txt"; + private final String destinationFolderLocation = "src/test/resources/destinationFolder"; + + @BeforeEach + public void createFolderWithSubfolderAndFile() throws IOException { + Files.createDirectories(Paths.get(sourceFolderLocation)); + Files.createDirectories(Paths.get(sourceFolderLocation + subFolderName)); + Files.createFile(Paths.get(sourceFolderLocation + subFolderName + fileName)); + } + + @Test + public void whenSourceFolderExists_thenFolderIsFullyCopied() throws IOException { + ApacheCommons.copyDirectory(sourceFolderLocation, destinationFolderLocation); + + assertTrue(new File(destinationFolderLocation).exists()); + assertTrue(new File(destinationFolderLocation + subFolderName).exists()); + assertTrue(new File(destinationFolderLocation + subFolderName + fileName).exists()); + } + + @Test + public void whenSourceFolderDoesNotExist_thenExceptionIsThrown() { + assertThrows(Exception.class, () -> ApacheCommons.copyDirectory("nonExistingFolder", destinationFolderLocation)); + } + + @AfterEach + public void cleanUp() throws IOException { + Files.walk(Paths.get(sourceFolderLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + if (new File(destinationFolderLocation).exists()) { + Files.walk(Paths.get(destinationFolderLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + +} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java new file mode 100644 index 0000000000..ba45fd3cd0 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.copyfolder; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class CoreOldUnitTest { + + private final String sourceFolderLocation = "src/test/resources/sourceFolder"; + private final String subFolderName = "/childFolder"; + private final String fileName = "/file.txt"; + private final String destinationFolderLocation = "src/test/resources/destinationFolder"; + + @BeforeEach + public void createFolderWithSubfolderAndFile() throws IOException { + Files.createDirectories(Paths.get(sourceFolderLocation)); + Files.createDirectories(Paths.get(sourceFolderLocation + subFolderName)); + Files.createFile(Paths.get(sourceFolderLocation + subFolderName + fileName)); + } + + @Test + public void whenSourceFolderExists_thenFolderIsFullyCopied() throws IOException { + File sourceFolder = new File(sourceFolderLocation); + File destinationFolder = new File(destinationFolderLocation); + CoreOld.copyDirectoryJavaUnder7(sourceFolder, destinationFolder); + + assertTrue(new File(destinationFolderLocation).exists()); + assertTrue(new File(destinationFolderLocation + subFolderName).exists()); + assertTrue(new File(destinationFolderLocation + subFolderName + fileName).exists()); + } + + @Test + public void whenSourceFolderDoesNotExist_thenExceptionIsThrown() throws IOException { + File sourceFolder = new File("nonExistingFolder"); + File destinationFolder = new File(destinationFolderLocation); + assertThrows(IOException.class, () -> CoreOld.copyDirectoryJavaUnder7(sourceFolder, destinationFolder)); + } + + @AfterEach + public void cleanUp() throws IOException { + Files.walk(Paths.get(sourceFolderLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + if (new File(destinationFolderLocation).exists()) { + Files.walk(Paths.get(destinationFolderLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + +} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java new file mode 100644 index 0000000000..162811912c --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.copyfolder; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class JavaNioUnitTest { + + private final String sourceFolderLocation = "src/test/resources/sourceFolder"; + private final String subFolderName = "/childFolder"; + private final String fileName = "/file.txt"; + private final String destinationFolderLocation = "src/test/resources/destinationFolder"; + + @BeforeEach + public void createFolderWithSubfolderAndFile() throws IOException { + Files.createDirectories(Paths.get(sourceFolderLocation)); + Files.createDirectories(Paths.get(sourceFolderLocation + subFolderName)); + Files.createFile(Paths.get(sourceFolderLocation + subFolderName + fileName)); + } + + @Test + public void whenSourceFolderExists_thenFolderIsFullyCopied() throws IOException { + JavaNio.copyDirectory(sourceFolderLocation, destinationFolderLocation); + + assertTrue(new File(destinationFolderLocation).exists()); + assertTrue(new File(destinationFolderLocation + subFolderName).exists()); + assertTrue(new File(destinationFolderLocation + subFolderName + fileName).exists()); + } + + @Test + public void whenSourceFolderDoesNotExist_thenExceptionIsThrown() { + assertThrows(IOException.class, () -> JavaNio.copyDirectory("nonExistingFolder", destinationFolderLocation)); + } + + @AfterEach + public void cleanUp() throws IOException { + Files.walk(Paths.get(sourceFolderLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + if (new File(destinationFolderLocation).exists()) { + Files.walk(Paths.get(destinationFolderLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + +} From 0423536cf417fdbd1c380b5ae4b6fb685d6b1b4f Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 28 Jul 2020 06:01:54 +0200 Subject: [PATCH 091/155] JAVA-2113: Split or move spring-resttemplate module (#9753) * JAVA-2113: Move Proxies With RestTemplate to spring-resttemplate-2 * JAVA-2113: Move A Custom Media Type for a Spring REST API to spring-resttemplate-2 * JAVA-2113: Move RestTemplate Post Request with JSON to spring-resttemplate-2 * JAVA-2113: Move Download an Image or a File with Spring MVC to spring-boot-mvc-3 * JAVA-2113: Fix the test --- spring-boot-modules/spring-boot-mvc-3/README.md | 1 + spring-boot-modules/spring-boot-mvc-3/pom.xml | 9 +++++++++ .../baeldung/produceimage/ImageApplication.java | 0 .../controller/DataProducerController.java | 0 spring-resttemplate-2/README.md | 3 +++ .../RestTemplateConfigurationApplication.java | 13 +++++++++++++ .../resttemplate/web/controller/PersonAPI.java | 0 .../baeldung/resttemplate/web/dto/Person.java | 0 .../resttemplate/web/service/PersonService.java | 0 .../web/service/PersonServiceImpl.java | 0 .../baeldung/sampleapp/config/WebConfig.java | 17 +++++++++++++++++ .../mediatypes/CustomMediaTypeController.java | 0 .../sampleapp/web/dto/BaeldungItem.java | 0 .../sampleapp/web/dto/BaeldungItemV2.java | 0 .../postjson/PersonAPILiveTest.java | 0 .../proxy/RequestFactoryLiveTest.java | 0 .../proxy/RestTemplateCustomizerLiveTest.java | 0 ...ustomMediaTypeControllerIntegrationTest.java | 0 .../CustomMediaTypeControllerLiveTest.java | 0 .../web/controller/mediatypes/TestConfig.java | 0 spring-resttemplate/README.md | 5 ----- .../java/com/baeldung/SpringContextTest.java | 4 +--- 22 files changed, 44 insertions(+), 8 deletions(-) rename {spring-resttemplate => spring-boot-modules/spring-boot-mvc-3}/src/main/java/com/baeldung/produceimage/ImageApplication.java (100%) rename {spring-resttemplate => spring-boot-modules/spring-boot-mvc-3}/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java (100%) create mode 100644 spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/resttemplate/web/dto/Person.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java (100%) create mode 100644 spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/config/WebConfig.java rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java (100%) rename {spring-resttemplate => spring-resttemplate-2}/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java (100%) diff --git a/spring-boot-modules/spring-boot-mvc-3/README.md b/spring-boot-modules/spring-boot-mvc-3/README.md index 58a3008966..0562224337 100644 --- a/spring-boot-modules/spring-boot-mvc-3/README.md +++ b/spring-boot-modules/spring-boot-mvc-3/README.md @@ -5,4 +5,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. ### Relevant Articles: - [Circular View Path Error](https://www.baeldung.com/spring-circular-view-path-error) +- [Download an Image or a File with Spring MVC](https://www.baeldung.com/spring-controller-return-image-file) - More articles: [[prev -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot-mvc-3/pom.xml b/spring-boot-modules/spring-boot-mvc-3/pom.xml index 71b7383ef4..31c43461d2 100644 --- a/spring-boot-modules/spring-boot-mvc-3/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-3/pom.xml @@ -26,6 +26,15 @@ org.springframework.boot spring-boot-starter-thymeleaf + + commons-io + commons-io + ${commons-io.version} + + + 2.7 + + \ No newline at end of file diff --git a/spring-resttemplate/src/main/java/com/baeldung/produceimage/ImageApplication.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/produceimage/ImageApplication.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/produceimage/ImageApplication.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/produceimage/ImageApplication.java diff --git a/spring-resttemplate/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java b/spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java rename to spring-boot-modules/spring-boot-mvc-3/src/main/java/com/baeldung/produceimage/controller/DataProducerController.java diff --git a/spring-resttemplate-2/README.md b/spring-resttemplate-2/README.md index d7a8a8633a..e1e0ba40b0 100644 --- a/spring-resttemplate-2/README.md +++ b/spring-resttemplate-2/README.md @@ -5,3 +5,6 @@ This module contains articles about Spring RestTemplate ### Relevant Articles: - [Spring RestTemplate Request/Response Logging](https://www.baeldung.com/spring-resttemplate-logging) +- [Proxies With RestTemplate](https://www.baeldung.com/java-resttemplate-proxy) +- [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type) +- [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) diff --git a/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java b/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java new file mode 100644 index 0000000000..8df3c13d7b --- /dev/null +++ b/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/RestTemplateConfigurationApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.resttemplate; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RestTemplateConfigurationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestTemplateConfigurationApplication.class, args); + } +} diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java b/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java rename to spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java b/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/dto/Person.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/dto/Person.java rename to spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/dto/Person.java diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java b/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java rename to spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/service/PersonService.java diff --git a/spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java b/spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java rename to spring-resttemplate-2/src/main/java/com/baeldung/resttemplate/web/service/PersonServiceImpl.java diff --git a/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/config/WebConfig.java b/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/config/WebConfig.java new file mode 100644 index 0000000000..cac12c6978 --- /dev/null +++ b/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/config/WebConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.sampleapp.config; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +@ComponentScan({ "com.baeldung.sampleapp.web" }) +public class WebConfig implements WebMvcConfigurer { + + public WebConfig() { + super(); + } + +} diff --git a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java b/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java rename to spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/controller/mediatypes/CustomMediaTypeController.java diff --git a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java b/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java rename to spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItem.java diff --git a/spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java b/spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java similarity index 100% rename from spring-resttemplate/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java rename to spring-resttemplate-2/src/main/java/com/baeldung/sampleapp/web/dto/BaeldungItemV2.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java b/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java similarity index 100% rename from spring-resttemplate/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java rename to spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java b/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java similarity index 100% rename from spring-resttemplate/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java rename to spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RequestFactoryLiveTest.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java b/spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java similarity index 100% rename from spring-resttemplate/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java rename to spring-resttemplate-2/src/test/java/com/baeldung/resttemplate/proxy/RestTemplateCustomizerLiveTest.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java b/spring-resttemplate-2/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java similarity index 100% rename from spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java rename to spring-resttemplate-2/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerIntegrationTest.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java b/spring-resttemplate-2/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java similarity index 100% rename from spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java rename to spring-resttemplate-2/src/test/java/com/baeldung/web/controller/mediatypes/CustomMediaTypeControllerLiveTest.java diff --git a/spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java b/spring-resttemplate-2/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java similarity index 100% rename from spring-resttemplate/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java rename to spring-resttemplate-2/src/test/java/com/baeldung/web/controller/mediatypes/TestConfig.java diff --git a/spring-resttemplate/README.md b/spring-resttemplate/README.md index bbfda4f6b8..952f35e90b 100644 --- a/spring-resttemplate/README.md +++ b/spring-resttemplate/README.md @@ -11,16 +11,11 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring RestTemplate Error Handling](https://www.baeldung.com/spring-rest-template-error-handling) - [Configure a RestTemplate with RestTemplateBuilder](https://www.baeldung.com/spring-rest-template-builder) - [Mocking a RestTemplate in Spring](https://www.baeldung.com/spring-mock-rest-template) -- [RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json) - [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) - [Using the Spring RestTemplate Interceptor](https://www.baeldung.com/spring-rest-template-interceptor) - [Uploading MultipartFile with Spring RestTemplate](https://www.baeldung.com/spring-rest-template-multipart-upload) - [Get and Post Lists of Objects with RestTemplate](https://www.baeldung.com/spring-rest-template-list) -- [Copy of RestTemplate Post Request with JSON](https://www.baeldung.com/spring-resttemplate-post-json-test) - [HTTP PUT vs HTTP PATCH in a REST API](https://www.baeldung.com/http-put-patch-difference-spring) -- [A Custom Media Type for a Spring REST API](https://www.baeldung.com/spring-rest-custom-media-type) -- [Download an Image or a File with Spring MVC](https://www.baeldung.com/spring-controller-return-image-file) -- [Proxies With RestTemplate](https://www.baeldung.com/java-resttemplate-proxy) ### NOTE: diff --git a/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java b/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java index 19d5eabd2b..43901cf37f 100644 --- a/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-resttemplate/src/test/java/com/baeldung/SpringContextTest.java @@ -5,12 +5,10 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.produceimage.ImageApplication; import com.baeldung.responseheaders.ResponseHeadersApplication; @RunWith(SpringRunner.class) -@SpringBootTest(classes = { ImageApplication.class, - ResponseHeadersApplication.class, +@SpringBootTest(classes = { ResponseHeadersApplication.class, com.baeldung.web.upload.app.UploadApplication.class, }) public class SpringContextTest { From 784ea2b061cf91622131eb6c0b50d75908f055fe Mon Sep 17 00:00:00 2001 From: Maja Joksovic Date: Tue, 28 Jul 2020 08:26:32 +0200 Subject: [PATCH 092/155] clean-up --- .../ApacheCommons.java | 8 +-- .../CoreOld.java | 12 ++-- .../JavaNio.java | 2 +- .../copydirectory/ApacheCommonsUnitTest.java | 59 +++++++++++++++++ .../copydirectory/CoreOldUnitTest.java | 63 +++++++++++++++++++ .../copydirectory/JavaNioUnitTest.java | 59 +++++++++++++++++ .../copyfolder/ApacheCommonsUnitTest.java | 59 ----------------- .../baeldung/copyfolder/CoreOldUnitTest.java | 63 ------------------- .../baeldung/copyfolder/JavaNioUnitTest.java | 59 ----------------- 9 files changed, 192 insertions(+), 192 deletions(-) rename core-java-modules/core-java-io-3/src/main/java/com/baeldung/{copyfolder => copydirectory}/ApacheCommons.java (51%) rename core-java-modules/core-java-io-3/src/main/java/com/baeldung/{copyfolder => copydirectory}/CoreOld.java (69%) rename core-java-modules/core-java-io-3/src/main/java/com/baeldung/{copyfolder => copydirectory}/JavaNio.java (94%) create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/ApacheCommonsUnitTest.java create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/CoreOldUnitTest.java create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/JavaNioUnitTest.java delete mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java delete mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java delete mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/ApacheCommons.java similarity index 51% rename from core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java rename to core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/ApacheCommons.java index 67af0594a4..b8aa283b48 100644 --- a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/ApacheCommons.java +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/ApacheCommons.java @@ -1,4 +1,4 @@ -package com.baeldung.copyfolder; +package com.baeldung.copydirectory; import java.io.File; import java.io.IOException; @@ -8,8 +8,8 @@ import org.apache.commons.io.FileUtils; public class ApacheCommons { public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { - File sourceFolder = new File(sourceDirectoryLocation); - File destinationFolder = new File(destinationDirectoryLocation); - FileUtils.copyDirectory(sourceFolder, destinationFolder); + File sourceDirectory = new File(sourceDirectoryLocation); + File destinationDirectory = new File(destinationDirectoryLocation); + FileUtils.copyDirectory(sourceDirectory, destinationDirectory); } } diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/CoreOld.java similarity index 69% rename from core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java rename to core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/CoreOld.java index d1a0158db3..2070977534 100644 --- a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/CoreOld.java +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/CoreOld.java @@ -1,4 +1,4 @@ -package com.baeldung.copyfolder; +package com.baeldung.copydirectory; import java.io.File; import java.io.FileInputStream; @@ -17,12 +17,12 @@ public class CoreOld { } } - private static void copyDirectory(File sourceFolder, File destinationFolder) throws IOException { - if (!destinationFolder.exists()) { - destinationFolder.mkdir(); + private static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException { + if (!destinationDirectory.exists()) { + destinationDirectory.mkdir(); } - for (String f : sourceFolder.list()) { - copyDirectoryJavaUnder7(new File(sourceFolder, f), new File(destinationFolder, f)); + for (String f : sourceDirectory.list()) { + copyDirectoryJavaUnder7(new File(sourceDirectory, f), new File(destinationDirectory, f)); } } diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java similarity index 94% rename from core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java rename to core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java index 368118a943..3f28bf0c9d 100644 --- a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copyfolder/JavaNio.java +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java @@ -1,4 +1,4 @@ -package com.baeldung.copyfolder; +package com.baeldung.copydirectory; import java.io.IOException; import java.nio.file.Files; diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/ApacheCommonsUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/ApacheCommonsUnitTest.java new file mode 100644 index 0000000000..3486a9af9d --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/ApacheCommonsUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.copydirectory; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ApacheCommonsUnitTest { + + private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory"; + private final String subDirectoryName = "/childDirectory"; + private final String fileName = "/file.txt"; + private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory"; + + @BeforeEach + public void createDirectoryWithSubdirectoryAndFile() throws IOException { + Files.createDirectories(Paths.get(sourceDirectoryLocation)); + Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName)); + Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName)); + } + + @Test + public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException { + ApacheCommons.copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation); + + assertTrue(new File(destinationDirectoryLocation).exists()); + assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists()); + assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists()); + } + + @Test + public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() { + assertThrows(Exception.class, () -> ApacheCommons.copyDirectory("nonExistingDirectory", destinationDirectoryLocation)); + } + + @AfterEach + public void cleanUp() throws IOException { + Files.walk(Paths.get(sourceDirectoryLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + if (new File(destinationDirectoryLocation).exists()) { + Files.walk(Paths.get(destinationDirectoryLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + +} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/CoreOldUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/CoreOldUnitTest.java new file mode 100644 index 0000000000..53ae216399 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/CoreOldUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.copydirectory; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class CoreOldUnitTest { + + private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory"; + private final String subDirectoryName = "/childDirectory"; + private final String fileName = "/file.txt"; + private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory"; + + @BeforeEach + public void createDirectoryWithSubdirectoryAndFile() throws IOException { + Files.createDirectories(Paths.get(sourceDirectoryLocation)); + Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName)); + Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName)); + } + + @Test + public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException { + File sourceDirectory = new File(sourceDirectoryLocation); + File destinationDirectory = new File(destinationDirectoryLocation); + CoreOld.copyDirectoryJavaUnder7(sourceDirectory, destinationDirectory); + + assertTrue(new File(destinationDirectoryLocation).exists()); + assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists()); + assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists()); + } + + @Test + public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() throws IOException { + File sourceDirectory = new File("nonExistingDirectory"); + File destinationDirectory = new File(destinationDirectoryLocation); + assertThrows(IOException.class, () -> CoreOld.copyDirectoryJavaUnder7(sourceDirectory, destinationDirectory)); + } + + @AfterEach + public void cleanUp() throws IOException { + Files.walk(Paths.get(sourceDirectoryLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + if (new File(destinationDirectoryLocation).exists()) { + Files.walk(Paths.get(destinationDirectoryLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + +} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/JavaNioUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/JavaNioUnitTest.java new file mode 100644 index 0000000000..8d1eea53c9 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copydirectory/JavaNioUnitTest.java @@ -0,0 +1,59 @@ +package com.baeldung.copydirectory; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class JavaNioUnitTest { + + private final String sourceDirectoryLocation = "src/test/resources/sourceDirectory"; + private final String subDirectoryName = "/childDirectory"; + private final String fileName = "/file.txt"; + private final String destinationDirectoryLocation = "src/test/resources/destinationDirectory"; + + @BeforeEach + public void createDirectoryWithSubdirectoryAndFile() throws IOException { + Files.createDirectories(Paths.get(sourceDirectoryLocation)); + Files.createDirectories(Paths.get(sourceDirectoryLocation + subDirectoryName)); + Files.createFile(Paths.get(sourceDirectoryLocation + subDirectoryName + fileName)); + } + + @Test + public void whenSourceDirectoryExists_thenDirectoryIsFullyCopied() throws IOException { + JavaNio.copyDirectory(sourceDirectoryLocation, destinationDirectoryLocation); + + assertTrue(new File(destinationDirectoryLocation).exists()); + assertTrue(new File(destinationDirectoryLocation + subDirectoryName).exists()); + assertTrue(new File(destinationDirectoryLocation + subDirectoryName + fileName).exists()); + } + + @Test + public void whenSourceDirectoryDoesNotExist_thenExceptionIsThrown() { + assertThrows(IOException.class, () -> JavaNio.copyDirectory("nonExistingDirectory", destinationDirectoryLocation)); + } + + @AfterEach + public void cleanUp() throws IOException { + Files.walk(Paths.get(sourceDirectoryLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + if (new File(destinationDirectoryLocation).exists()) { + Files.walk(Paths.get(destinationDirectoryLocation)) + .sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + } + +} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java deleted file mode 100644 index 71e4c52104..0000000000 --- a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/ApacheCommonsUnitTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.copyfolder; - -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Comparator; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class ApacheCommonsUnitTest { - - private final String sourceFolderLocation = "src/test/resources/sourceFolder"; - private final String subFolderName = "/childFolder"; - private final String fileName = "/file.txt"; - private final String destinationFolderLocation = "src/test/resources/destinationFolder"; - - @BeforeEach - public void createFolderWithSubfolderAndFile() throws IOException { - Files.createDirectories(Paths.get(sourceFolderLocation)); - Files.createDirectories(Paths.get(sourceFolderLocation + subFolderName)); - Files.createFile(Paths.get(sourceFolderLocation + subFolderName + fileName)); - } - - @Test - public void whenSourceFolderExists_thenFolderIsFullyCopied() throws IOException { - ApacheCommons.copyDirectory(sourceFolderLocation, destinationFolderLocation); - - assertTrue(new File(destinationFolderLocation).exists()); - assertTrue(new File(destinationFolderLocation + subFolderName).exists()); - assertTrue(new File(destinationFolderLocation + subFolderName + fileName).exists()); - } - - @Test - public void whenSourceFolderDoesNotExist_thenExceptionIsThrown() { - assertThrows(Exception.class, () -> ApacheCommons.copyDirectory("nonExistingFolder", destinationFolderLocation)); - } - - @AfterEach - public void cleanUp() throws IOException { - Files.walk(Paths.get(sourceFolderLocation)) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - if (new File(destinationFolderLocation).exists()) { - Files.walk(Paths.get(destinationFolderLocation)) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } - -} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java deleted file mode 100644 index ba45fd3cd0..0000000000 --- a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/CoreOldUnitTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.baeldung.copyfolder; - -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Comparator; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class CoreOldUnitTest { - - private final String sourceFolderLocation = "src/test/resources/sourceFolder"; - private final String subFolderName = "/childFolder"; - private final String fileName = "/file.txt"; - private final String destinationFolderLocation = "src/test/resources/destinationFolder"; - - @BeforeEach - public void createFolderWithSubfolderAndFile() throws IOException { - Files.createDirectories(Paths.get(sourceFolderLocation)); - Files.createDirectories(Paths.get(sourceFolderLocation + subFolderName)); - Files.createFile(Paths.get(sourceFolderLocation + subFolderName + fileName)); - } - - @Test - public void whenSourceFolderExists_thenFolderIsFullyCopied() throws IOException { - File sourceFolder = new File(sourceFolderLocation); - File destinationFolder = new File(destinationFolderLocation); - CoreOld.copyDirectoryJavaUnder7(sourceFolder, destinationFolder); - - assertTrue(new File(destinationFolderLocation).exists()); - assertTrue(new File(destinationFolderLocation + subFolderName).exists()); - assertTrue(new File(destinationFolderLocation + subFolderName + fileName).exists()); - } - - @Test - public void whenSourceFolderDoesNotExist_thenExceptionIsThrown() throws IOException { - File sourceFolder = new File("nonExistingFolder"); - File destinationFolder = new File(destinationFolderLocation); - assertThrows(IOException.class, () -> CoreOld.copyDirectoryJavaUnder7(sourceFolder, destinationFolder)); - } - - @AfterEach - public void cleanUp() throws IOException { - Files.walk(Paths.get(sourceFolderLocation)) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - if (new File(destinationFolderLocation).exists()) { - Files.walk(Paths.get(destinationFolderLocation)) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } - -} diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java deleted file mode 100644 index 162811912c..0000000000 --- a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/copyfolder/JavaNioUnitTest.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baeldung.copyfolder; - -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Comparator; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class JavaNioUnitTest { - - private final String sourceFolderLocation = "src/test/resources/sourceFolder"; - private final String subFolderName = "/childFolder"; - private final String fileName = "/file.txt"; - private final String destinationFolderLocation = "src/test/resources/destinationFolder"; - - @BeforeEach - public void createFolderWithSubfolderAndFile() throws IOException { - Files.createDirectories(Paths.get(sourceFolderLocation)); - Files.createDirectories(Paths.get(sourceFolderLocation + subFolderName)); - Files.createFile(Paths.get(sourceFolderLocation + subFolderName + fileName)); - } - - @Test - public void whenSourceFolderExists_thenFolderIsFullyCopied() throws IOException { - JavaNio.copyDirectory(sourceFolderLocation, destinationFolderLocation); - - assertTrue(new File(destinationFolderLocation).exists()); - assertTrue(new File(destinationFolderLocation + subFolderName).exists()); - assertTrue(new File(destinationFolderLocation + subFolderName + fileName).exists()); - } - - @Test - public void whenSourceFolderDoesNotExist_thenExceptionIsThrown() { - assertThrows(IOException.class, () -> JavaNio.copyDirectory("nonExistingFolder", destinationFolderLocation)); - } - - @AfterEach - public void cleanUp() throws IOException { - Files.walk(Paths.get(sourceFolderLocation)) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - if (new File(destinationFolderLocation).exists()) { - Files.walk(Paths.get(destinationFolderLocation)) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - } - } - -} From 000ce564ffe3e9191285d56854b23b8b4ea9455e Mon Sep 17 00:00:00 2001 From: Maja Joksovic Date: Tue, 28 Jul 2020 10:03:46 +0200 Subject: [PATCH 093/155] changed variable names --- .../src/main/java/com/baeldung/copydirectory/JavaNio.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java index 3f28bf0c9d..fe1eb59c64 100644 --- a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java @@ -9,11 +9,11 @@ public class JavaNio { public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { Files.walk(Paths.get(sourceDirectoryLocation)) - .forEach(a -> { - Path b = Paths.get(destinationDirectoryLocation, a.toString() + .forEach(source -> { + Path destination = Paths.get(destinationDirectoryLocation, source.toString() .substring(sourceDirectoryLocation.length())); try { - Files.copy(a, b); + Files.copy(source, destination); } catch (IOException e) { e.printStackTrace(); } From 0cade733ca1f44f2d726dff8290708820fbd3ccd Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Tue, 28 Jul 2020 17:34:46 +0530 Subject: [PATCH 094/155] JAVA-2154: Create guava-parent module and organize guava modules (#9782) * JAVA-2154: Removed module, now split into guava-utilities and guava-core * JAVA-2154: Removed module, articles moved to new module guava-core * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved module inside guava-modules * JAVA-2154: Moved 1 article to guava-collections * JAVA-2154: New module guava-collections-list * JAVA-2154: New module guava-core * JAVA-2154: New module guava-utilities * JAVA-2154: Updated README, removed extra article reference * JAVA-2154: parent module pom changes * JAVA-2154: main pom changes - removed guava related modules as they have been shifted inside guava-modules * JAVA-2154: rearranged and moved module inside guava-modules folder --- guava-2/README.md | 7 -- guava-modules/guava-18/README.md | 5 +- guava-modules/guava-19/README.md | 2 - guava-modules/guava-21/README.md | 4 +- guava-modules/guava-21/pom.xml | 9 -- .../guava-collections-list/README.md | 8 ++ .../guava-collections-list}/pom.xml | 8 +- .../src/main/resources/logback.xml | 0 .../guava/lists/GuavaListsUnitTest.java | 0 .../CollectionApachePartitionUnitTest.java | 0 .../CollectionGuavaPartitionUnitTest.java | 0 .../CollectionJavaPartitionUnitTest.java | 0 .../guava-collections-map}/README.md | 0 .../guava-collections-map}/pom.xml | 4 +- .../com/baeldung/guava/mapmaker/Profile.java | 0 .../com/baeldung/guava/mapmaker/Session.java | 0 .../com/baeldung/guava/mapmaker/User.java | 0 .../ClassToInstanceMapUnitTest.java | 0 .../GuavaMapInitializeUnitTest.java | 0 .../guava/mapmaker/GuavaMapMakerUnitTest.java | 0 .../guava/maps/GuavaMapsUnitTest.java | 0 .../guava/multimap/GuavaMultiMapUnitTest.java | 0 .../guava/rangemap/GuavaRangeMapUnitTest.java | 0 .../guava-collections-set}/.gitignore | 0 .../guava-collections-set}/README.md | 0 .../guava-collections-set}/pom.xml | 4 +- .../com/baeldung/guava/GuavaMapFromSet.java | 0 .../guava/GuavaMapFromSetUnitTest.java | 0 .../baeldung/guava/GuavaMultiSetUnitTest.java | 0 .../baeldung/guava/GuavaRangeSetUnitTest.java | 0 .../guava/GuavaSetOperationsUnitTest.java | 0 .../guava-collections}/README.md | 3 +- guava-modules/guava-collections/pom.xml | 95 ++++++++++++++++++ .../src/main/resources/logback.xml | 0 .../GuavaCollectionsExamplesUnitTest.java | 0 ...avaFilterTransformCollectionsUnitTest.java | 0 .../guava/joinsplit/GuavaStringUnitTest.java | 0 .../GuavaOrderingExamplesUnitTest.java | 0 .../guava/ordering/GuavaOrderingUnitTest.java | 0 .../guava/queues/EvictingQueueUnitTest.java | 0 .../queues/MinMaxPriorityQueueUnitTest.java | 0 .../guava/table/GuavaTableUnitTest.java | 0 .../guava/zip/ZipCollectionUnitTest.java | 0 .../hamcrest/HamcrestExamplesUnitTest.java | 0 .../src/test/resources/test.out | 0 .../src/test/resources/test1.in | 0 .../src/test/resources/test1_1.in | 0 .../src/test/resources/test2.in | 0 .../src/test/resources/test_copy.in | 0 .../src/test/resources/test_le.txt | Bin guava-modules/guava-core/README.md | 10 ++ {guava-2 => guava-modules/guava-core}/pom.xml | 8 +- .../guava/memoizer/CostlySupplier.java | 0 .../baeldung/guava/memoizer/Factorial.java | 0 .../guava/memoizer/FibonacciSequence.java | 0 .../charmatcher/GuavaCharMatcherUnitTest.java | 0 .../GuavaFunctionalExamplesUnitTest.java | 2 +- .../memoizer}/GuavaMemoizerUnitTest.java | 2 +- .../GuavaPreConditionsUnitTest.java | 2 +- .../guava/throwables/ThrowablesUnitTest.java | 0 .../guava-core/src/test/resources}/.gitignore | 0 .../guava-core}/src/test/resources/test.out | 0 .../guava-core}/src/test/resources/test1.in | 0 .../guava-core}/src/test/resources/test1_1.in | 0 .../guava-core}/src/test/resources/test2.in | 0 .../src/test/resources/test_copy.in | 0 .../src/test/resources/test_le.txt | Bin .../guava-io}/README.md | 0 {guava-io => guava-modules/guava-io}/pom.xml | 4 +- .../GuavaCountingOutputStreamUnitTest.java | 0 .../com/baeldung/guava/GuavaIOUnitTest.java | 0 .../guava-io}/src/test/resources/test1.in | 0 .../guava-io}/src/test/resources/test1_1.in | 0 .../guava-io}/src/test/resources/test2.in | 0 .../guava-utilities}/.gitignore | 0 .../guava-utilities}/README.md | 9 +- .../guava-utilities}/pom.xml | 8 +- .../baeldung/guava/eventbus}/CustomEvent.java | 2 +- .../guava/eventbus}/EventListener.java | 2 +- .../src/main/resources/logback.xml | 19 ++++ .../bloomfilter}/BloomFilterUnitTest.java | 2 +- .../guava/cache}/GuavaCacheUnitTest.java | 2 +- .../GuavaCacheLoaderUnitTest.java | 2 +- .../eventbus}/GuavaEventBusUnitTest.java | 4 +- .../GuavaBigIntegerMathUnitTest.java | 2 +- .../mathutils}/GuavaDoubleMathUnitTest.java | 2 +- .../mathutils}/GuavaIntMathUnitTest.java | 2 +- .../mathutils}/GuavaLongMathUnitTest.java | 2 +- .../guava/mathutils}/GuavaMathUnitTest.java | 2 +- .../RateLimiterLongRunningUnitTest.java | 2 +- .../GuavaReflectionUtilsUnitTest.java | 2 +- .../src/test/resources/.gitignore | 0 .../src/test/resources/test.out | 0 .../src/test/resources/test1.in | 0 .../src/test/resources/test1_1.in | 0 .../src/test/resources/test2.in | 0 .../src/test/resources/test_copy.in | 0 .../src/test/resources/test_le.txt | Bin guava-modules/pom.xml | 7 ++ pom.xml | 15 +-- 100 files changed, 184 insertions(+), 79 deletions(-) delete mode 100644 guava-2/README.md create mode 100644 guava-modules/guava-collections-list/README.md rename {guava-collections => guava-modules/guava-collections-list}/pom.xml (93%) rename {guava-collections => guava-modules/guava-collections-list}/src/main/resources/logback.xml (100%) rename {guava-collections => guava-modules/guava-collections-list}/src/test/java/com/baeldung/guava/lists/GuavaListsUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections-list}/src/test/java/com/baeldung/guava/partition/CollectionApachePartitionUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections-list}/src/test/java/com/baeldung/guava/partition/CollectionGuavaPartitionUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections-list}/src/test/java/com/baeldung/guava/partition/CollectionJavaPartitionUnitTest.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/README.md (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/pom.xml (94%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/main/java/com/baeldung/guava/mapmaker/Profile.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/main/java/com/baeldung/guava/mapmaker/Session.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/main/java/com/baeldung/guava/mapmaker/User.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/test/java/com/baeldung/guava/classtoinstancemap/ClassToInstanceMapUnitTest.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/test/java/com/baeldung/guava/initializemaps/GuavaMapInitializeUnitTest.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/test/java/com/baeldung/guava/maps/GuavaMapsUnitTest.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/test/java/com/baeldung/guava/multimap/GuavaMultiMapUnitTest.java (100%) rename {guava-collections-map => guava-modules/guava-collections-map}/src/test/java/com/baeldung/guava/rangemap/GuavaRangeMapUnitTest.java (100%) rename {guava-2/src/test/resources => guava-modules/guava-collections-set}/.gitignore (100%) rename {guava-collections-set => guava-modules/guava-collections-set}/README.md (100%) rename {guava-collections-set => guava-modules/guava-collections-set}/pom.xml (94%) rename {guava-collections-set => guava-modules/guava-collections-set}/src/test/java/com/baeldung/guava/GuavaMapFromSet.java (100%) rename {guava-collections-set => guava-modules/guava-collections-set}/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java (100%) rename {guava-collections-set => guava-modules/guava-collections-set}/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java (100%) rename {guava-collections-set => guava-modules/guava-collections-set}/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java (100%) rename {guava-collections-set => guava-modules/guava-collections-set}/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/README.md (86%) create mode 100644 guava-modules/guava-collections/pom.xml rename {guava => guava-modules/guava-collections}/src/main/resources/logback.xml (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/collections/GuavaCollectionsExamplesUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/filtertransform/GuavaFilterTransformCollectionsUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/joinsplit/GuavaStringUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/ordering/GuavaOrderingExamplesUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/ordering/GuavaOrderingUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/queues/EvictingQueueUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/queues/MinMaxPriorityQueueUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/guava/table/GuavaTableUnitTest.java (100%) rename guava-modules/{guava-21 => guava-collections}/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java (100%) rename {guava-collections => guava-modules/guava-collections}/src/test/java/com/baeldung/hamcrest/HamcrestExamplesUnitTest.java (100%) rename {guava-2 => guava-modules/guava-collections}/src/test/resources/test.out (100%) rename {guava-2 => guava-modules/guava-collections}/src/test/resources/test1.in (100%) rename {guava-2 => guava-modules/guava-collections}/src/test/resources/test1_1.in (100%) rename {guava-2 => guava-modules/guava-collections}/src/test/resources/test2.in (100%) rename {guava-2 => guava-modules/guava-collections}/src/test/resources/test_copy.in (100%) rename {guava-2 => guava-modules/guava-collections}/src/test/resources/test_le.txt (100%) create mode 100644 guava-modules/guava-core/README.md rename {guava-2 => guava-modules/guava-core}/pom.xml (89%) rename {guava => guava-modules/guava-core}/src/main/java/com/baeldung/guava/memoizer/CostlySupplier.java (100%) rename {guava => guava-modules/guava-core}/src/main/java/com/baeldung/guava/memoizer/Factorial.java (100%) rename {guava => guava-modules/guava-core}/src/main/java/com/baeldung/guava/memoizer/FibonacciSequence.java (100%) rename {guava-2 => guava-modules/guava-core}/src/test/java/com/baeldung/guava/charmatcher/GuavaCharMatcherUnitTest.java (100%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-core/src/test/java/com/baeldung/guava/functional}/GuavaFunctionalExamplesUnitTest.java (99%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-core/src/test/java/com/baeldung/guava/memoizer}/GuavaMemoizerUnitTest.java (98%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-core/src/test/java/com/baeldung/guava/preconditions}/GuavaPreConditionsUnitTest.java (99%) rename {guava-2 => guava-modules/guava-core}/src/test/java/com/baeldung/guava/throwables/ThrowablesUnitTest.java (100%) rename {guava-collections-set => guava-modules/guava-core/src/test/resources}/.gitignore (100%) rename {guava-collections => guava-modules/guava-core}/src/test/resources/test.out (100%) rename {guava-collections => guava-modules/guava-core}/src/test/resources/test1.in (100%) rename {guava-collections => guava-modules/guava-core}/src/test/resources/test1_1.in (100%) rename {guava-collections => guava-modules/guava-core}/src/test/resources/test2.in (100%) rename {guava-collections => guava-modules/guava-core}/src/test/resources/test_copy.in (100%) rename {guava-collections => guava-modules/guava-core}/src/test/resources/test_le.txt (100%) rename {guava-io => guava-modules/guava-io}/README.md (100%) rename {guava-io => guava-modules/guava-io}/pom.xml (94%) rename {guava-io => guava-modules/guava-io}/src/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java (100%) rename {guava-io => guava-modules/guava-io}/src/test/java/com/baeldung/guava/GuavaIOUnitTest.java (100%) rename {guava-io => guava-modules/guava-io}/src/test/resources/test1.in (100%) rename {guava-io => guava-modules/guava-io}/src/test/resources/test1_1.in (100%) rename {guava-io => guava-modules/guava-io}/src/test/resources/test2.in (100%) rename {guava => guava-modules/guava-utilities}/.gitignore (100%) rename {guava => guava-modules/guava-utilities}/README.md (60%) rename {guava => guava-modules/guava-utilities}/pom.xml (92%) rename {guava/src/main/java/com/baeldung/guava => guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus}/CustomEvent.java (87%) rename {guava/src/main/java/com/baeldung/guava => guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus}/EventListener.java (96%) create mode 100644 guava-modules/guava-utilities/src/main/resources/logback.xml rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/bloomfilter}/BloomFilterUnitTest.java (97%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cache}/GuavaCacheUnitTest.java (99%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cacheloader}/GuavaCacheLoaderUnitTest.java (98%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/eventbus}/GuavaEventBusUnitTest.java (90%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils}/GuavaBigIntegerMathUnitTest.java (99%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils}/GuavaDoubleMathUnitTest.java (98%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils}/GuavaIntMathUnitTest.java (99%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils}/GuavaLongMathUnitTest.java (99%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils}/GuavaMathUnitTest.java (99%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/ratelimiter}/RateLimiterLongRunningUnitTest.java (98%) rename {guava/src/test/java/com/baeldung/guava => guava-modules/guava-utilities/src/test/java/com/baeldung/guava/reflectionutils}/GuavaReflectionUtilsUnitTest.java (99%) rename {guava => guava-modules/guava-utilities}/src/test/resources/.gitignore (100%) rename {guava => guava-modules/guava-utilities}/src/test/resources/test.out (100%) rename {guava => guava-modules/guava-utilities}/src/test/resources/test1.in (100%) rename {guava => guava-modules/guava-utilities}/src/test/resources/test1_1.in (100%) rename {guava => guava-modules/guava-utilities}/src/test/resources/test2.in (100%) rename {guava => guava-modules/guava-utilities}/src/test/resources/test_copy.in (100%) rename {guava => guava-modules/guava-utilities}/src/test/resources/test_le.txt (100%) diff --git a/guava-2/README.md b/guava-2/README.md deleted file mode 100644 index 32afc10916..0000000000 --- a/guava-2/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Guava - -This module contains articles a Google Guava - -### Relevant Articles: - -- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher) diff --git a/guava-modules/guava-18/README.md b/guava-modules/guava-18/README.md index fd5de4170a..bdd289b86f 100644 --- a/guava-modules/guava-18/README.md +++ b/guava-modules/guava-18/README.md @@ -1,8 +1,5 @@ -========= - -## Guava and Hamcrest Cookbooks and Examples +## Guava 18 ### Relevant Articles: -- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates) - [Guava 18: What’s New?](http://www.baeldung.com/whats-new-in-guava-18) diff --git a/guava-modules/guava-19/README.md b/guava-modules/guava-19/README.md index be9f2d72a4..6508410ba2 100644 --- a/guava-modules/guava-19/README.md +++ b/guava-modules/guava-19/README.md @@ -1,5 +1,3 @@ -========= - ## Guava 19 diff --git a/guava-modules/guava-21/README.md b/guava-modules/guava-21/README.md index 4e897325b6..ad70a180b0 100644 --- a/guava-modules/guava-21/README.md +++ b/guava-modules/guava-21/README.md @@ -1,4 +1,6 @@ +## Guava 21 + ### Relevant articles: + - [New Stream, Comparator and Collector in Guava 21](http://www.baeldung.com/guava-21-new) - [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent) -- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip) diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml index b126df99cb..b793f11a7f 100644 --- a/guava-modules/guava-21/pom.xml +++ b/guava-modules/guava-21/pom.xml @@ -13,17 +13,8 @@ ../ - - - org.jooq - jool - ${jool.version} - - - 21.0 - 0.9.12 \ No newline at end of file diff --git a/guava-modules/guava-collections-list/README.md b/guava-modules/guava-collections-list/README.md new file mode 100644 index 0000000000..d7f9ce2e32 --- /dev/null +++ b/guava-modules/guava-collections-list/README.md @@ -0,0 +1,8 @@ +## Guava Collections List examples + +This module contains articles about list collections in Guava + +### Relevant Articles: + +- [Partition a List in Java](https://www.baeldung.com/java-list-split) +- [Guava – Lists](https://www.baeldung.com/guava-lists) \ No newline at end of file diff --git a/guava-collections/pom.xml b/guava-modules/guava-collections-list/pom.xml similarity index 93% rename from guava-collections/pom.xml rename to guava-modules/guava-collections-list/pom.xml index 238ab60f84..cc52a5d48b 100644 --- a/guava-collections/pom.xml +++ b/guava-modules/guava-collections-list/pom.xml @@ -4,15 +4,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - guava-collections + guava-collections-list 0.1.0-SNAPSHOT - guava-collections + guava-collections-list com.baeldung - parent-java + guava-modules 0.0.1-SNAPSHOT - ../parent-java + ../ diff --git a/guava-collections/src/main/resources/logback.xml b/guava-modules/guava-collections-list/src/main/resources/logback.xml similarity index 100% rename from guava-collections/src/main/resources/logback.xml rename to guava-modules/guava-collections-list/src/main/resources/logback.xml diff --git a/guava-collections/src/test/java/com/baeldung/guava/lists/GuavaListsUnitTest.java b/guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/lists/GuavaListsUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/lists/GuavaListsUnitTest.java rename to guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/lists/GuavaListsUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/partition/CollectionApachePartitionUnitTest.java b/guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/partition/CollectionApachePartitionUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/partition/CollectionApachePartitionUnitTest.java rename to guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/partition/CollectionApachePartitionUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/partition/CollectionGuavaPartitionUnitTest.java b/guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/partition/CollectionGuavaPartitionUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/partition/CollectionGuavaPartitionUnitTest.java rename to guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/partition/CollectionGuavaPartitionUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/partition/CollectionJavaPartitionUnitTest.java b/guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/partition/CollectionJavaPartitionUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/partition/CollectionJavaPartitionUnitTest.java rename to guava-modules/guava-collections-list/src/test/java/com/baeldung/guava/partition/CollectionJavaPartitionUnitTest.java diff --git a/guava-collections-map/README.md b/guava-modules/guava-collections-map/README.md similarity index 100% rename from guava-collections-map/README.md rename to guava-modules/guava-collections-map/README.md diff --git a/guava-collections-map/pom.xml b/guava-modules/guava-collections-map/pom.xml similarity index 94% rename from guava-collections-map/pom.xml rename to guava-modules/guava-collections-map/pom.xml index 4a95234d5c..82d634265b 100644 --- a/guava-collections-map/pom.xml +++ b/guava-modules/guava-collections-map/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-java + guava-modules 0.0.1-SNAPSHOT - ../parent-java + ../ diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java b/guava-modules/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java similarity index 100% rename from guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java rename to guava-modules/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Profile.java diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java b/guava-modules/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java similarity index 100% rename from guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java rename to guava-modules/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/Session.java diff --git a/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java b/guava-modules/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java similarity index 100% rename from guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java rename to guava-modules/guava-collections-map/src/main/java/com/baeldung/guava/mapmaker/User.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/classtoinstancemap/ClassToInstanceMapUnitTest.java b/guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/classtoinstancemap/ClassToInstanceMapUnitTest.java similarity index 100% rename from guava-collections-map/src/test/java/com/baeldung/guava/classtoinstancemap/ClassToInstanceMapUnitTest.java rename to guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/classtoinstancemap/ClassToInstanceMapUnitTest.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/initializemaps/GuavaMapInitializeUnitTest.java b/guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/initializemaps/GuavaMapInitializeUnitTest.java similarity index 100% rename from guava-collections-map/src/test/java/com/baeldung/guava/initializemaps/GuavaMapInitializeUnitTest.java rename to guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/initializemaps/GuavaMapInitializeUnitTest.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java b/guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java similarity index 100% rename from guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java rename to guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/mapmaker/GuavaMapMakerUnitTest.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/maps/GuavaMapsUnitTest.java b/guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/maps/GuavaMapsUnitTest.java similarity index 100% rename from guava-collections-map/src/test/java/com/baeldung/guava/maps/GuavaMapsUnitTest.java rename to guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/maps/GuavaMapsUnitTest.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/multimap/GuavaMultiMapUnitTest.java b/guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/multimap/GuavaMultiMapUnitTest.java similarity index 100% rename from guava-collections-map/src/test/java/com/baeldung/guava/multimap/GuavaMultiMapUnitTest.java rename to guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/multimap/GuavaMultiMapUnitTest.java diff --git a/guava-collections-map/src/test/java/com/baeldung/guava/rangemap/GuavaRangeMapUnitTest.java b/guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/rangemap/GuavaRangeMapUnitTest.java similarity index 100% rename from guava-collections-map/src/test/java/com/baeldung/guava/rangemap/GuavaRangeMapUnitTest.java rename to guava-modules/guava-collections-map/src/test/java/com/baeldung/guava/rangemap/GuavaRangeMapUnitTest.java diff --git a/guava-2/src/test/resources/.gitignore b/guava-modules/guava-collections-set/.gitignore similarity index 100% rename from guava-2/src/test/resources/.gitignore rename to guava-modules/guava-collections-set/.gitignore diff --git a/guava-collections-set/README.md b/guava-modules/guava-collections-set/README.md similarity index 100% rename from guava-collections-set/README.md rename to guava-modules/guava-collections-set/README.md diff --git a/guava-collections-set/pom.xml b/guava-modules/guava-collections-set/pom.xml similarity index 94% rename from guava-collections-set/pom.xml rename to guava-modules/guava-collections-set/pom.xml index af46400555..8f58148e41 100644 --- a/guava-collections-set/pom.xml +++ b/guava-modules/guava-collections-set/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-java + guava-modules 0.0.1-SNAPSHOT - ../parent-java + ../ diff --git a/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java b/guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java similarity index 100% rename from guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java rename to guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSet.java diff --git a/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java b/guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java similarity index 100% rename from guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java rename to guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMapFromSetUnitTest.java diff --git a/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java b/guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java similarity index 100% rename from guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java rename to guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaMultiSetUnitTest.java diff --git a/guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java b/guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java similarity index 100% rename from guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java rename to guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaRangeSetUnitTest.java diff --git a/guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java b/guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java similarity index 100% rename from guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java rename to guava-modules/guava-collections-set/src/test/java/com/baeldung/guava/GuavaSetOperationsUnitTest.java diff --git a/guava-collections/README.md b/guava-modules/guava-collections/README.md similarity index 86% rename from guava-collections/README.md rename to guava-modules/guava-collections/README.md index 51731d7db7..474ded6f33 100644 --- a/guava-collections/README.md +++ b/guava-modules/guava-collections/README.md @@ -8,9 +8,8 @@ This module contains articles about Google Guava collections - [Guava Ordering Cookbook](https://www.baeldung.com/guava-order) - [Guide to Guava’s Ordering](https://www.baeldung.com/guava-ordering) - [Hamcrest Collections Cookbook](https://www.baeldung.com/hamcrest-collections-arrays) -- [Partition a List in Java](https://www.baeldung.com/java-list-split) - [Filtering and Transforming Collections in Guava](https://www.baeldung.com/guava-filter-and-transform-a-collection) - [Guava – Join and Split Collections](https://www.baeldung.com/guava-joiner-and-splitter-tutorial) -- [Guava – Lists](https://www.baeldung.com/guava-lists) - [Guide to Guava MinMaxPriorityQueue and EvictingQueue](https://www.baeldung.com/guava-minmax-priority-queue-and-evicting-queue) - [Guide to Guava Table](https://www.baeldung.com/guava-table) +- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip) diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml new file mode 100644 index 0000000000..53c55dc655 --- /dev/null +++ b/guava-modules/guava-collections/pom.xml @@ -0,0 +1,95 @@ + + + 4.0.0 + guava-collections + 0.1.0-SNAPSHOT + guava-collections + + + com.baeldung + guava-modules + 0.0.1-SNAPSHOT + ../ + + + + + + org.apache.commons + commons-collections4 + ${commons-collections4.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.jooq + jool + ${jool.version} + + + + + org.junit.jupiter + junit-jupiter + ${junit-jupiter.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit-jupiter.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + org.hamcrest + java-hamcrest + ${java-hamcrest.version} + test + + + + + guava-collections + + + + src/main/resources + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + + + + 4.1 + 0.9.12 + + + 3.6.1 + 2.0.0.0 + 5.6.2 + + + \ No newline at end of file diff --git a/guava/src/main/resources/logback.xml b/guava-modules/guava-collections/src/main/resources/logback.xml similarity index 100% rename from guava/src/main/resources/logback.xml rename to guava-modules/guava-collections/src/main/resources/logback.xml diff --git a/guava-collections/src/test/java/com/baeldung/guava/collections/GuavaCollectionsExamplesUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/collections/GuavaCollectionsExamplesUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/collections/GuavaCollectionsExamplesUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/collections/GuavaCollectionsExamplesUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/filtertransform/GuavaFilterTransformCollectionsUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/filtertransform/GuavaFilterTransformCollectionsUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/filtertransform/GuavaFilterTransformCollectionsUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/filtertransform/GuavaFilterTransformCollectionsUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/joinsplit/GuavaStringUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/joinsplit/GuavaStringUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/joinsplit/GuavaStringUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/joinsplit/GuavaStringUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingExamplesUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingExamplesUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingExamplesUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingExamplesUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/ordering/GuavaOrderingUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/queues/EvictingQueueUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/queues/EvictingQueueUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/queues/EvictingQueueUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/queues/EvictingQueueUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/queues/MinMaxPriorityQueueUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/queues/MinMaxPriorityQueueUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/queues/MinMaxPriorityQueueUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/queues/MinMaxPriorityQueueUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/guava/table/GuavaTableUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/table/GuavaTableUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/guava/table/GuavaTableUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/table/GuavaTableUnitTest.java diff --git a/guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java similarity index 100% rename from guava-modules/guava-21/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/guava/zip/ZipCollectionUnitTest.java diff --git a/guava-collections/src/test/java/com/baeldung/hamcrest/HamcrestExamplesUnitTest.java b/guava-modules/guava-collections/src/test/java/com/baeldung/hamcrest/HamcrestExamplesUnitTest.java similarity index 100% rename from guava-collections/src/test/java/com/baeldung/hamcrest/HamcrestExamplesUnitTest.java rename to guava-modules/guava-collections/src/test/java/com/baeldung/hamcrest/HamcrestExamplesUnitTest.java diff --git a/guava-2/src/test/resources/test.out b/guava-modules/guava-collections/src/test/resources/test.out similarity index 100% rename from guava-2/src/test/resources/test.out rename to guava-modules/guava-collections/src/test/resources/test.out diff --git a/guava-2/src/test/resources/test1.in b/guava-modules/guava-collections/src/test/resources/test1.in similarity index 100% rename from guava-2/src/test/resources/test1.in rename to guava-modules/guava-collections/src/test/resources/test1.in diff --git a/guava-2/src/test/resources/test1_1.in b/guava-modules/guava-collections/src/test/resources/test1_1.in similarity index 100% rename from guava-2/src/test/resources/test1_1.in rename to guava-modules/guava-collections/src/test/resources/test1_1.in diff --git a/guava-2/src/test/resources/test2.in b/guava-modules/guava-collections/src/test/resources/test2.in similarity index 100% rename from guava-2/src/test/resources/test2.in rename to guava-modules/guava-collections/src/test/resources/test2.in diff --git a/guava-2/src/test/resources/test_copy.in b/guava-modules/guava-collections/src/test/resources/test_copy.in similarity index 100% rename from guava-2/src/test/resources/test_copy.in rename to guava-modules/guava-collections/src/test/resources/test_copy.in diff --git a/guava-2/src/test/resources/test_le.txt b/guava-modules/guava-collections/src/test/resources/test_le.txt similarity index 100% rename from guava-2/src/test/resources/test_le.txt rename to guava-modules/guava-collections/src/test/resources/test_le.txt diff --git a/guava-modules/guava-core/README.md b/guava-modules/guava-core/README.md new file mode 100644 index 0000000000..59391ca076 --- /dev/null +++ b/guava-modules/guava-core/README.md @@ -0,0 +1,10 @@ +## Guava Core + +This module contains articles about core or base functionality provided by Google Guava + +### Relevant Articles: +- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables) +- [Guava CharMatcher](https://www.baeldung.com/guava-string-charmatcher) +- [Guide to Guava’s PreConditions](https://www.baeldung.com/guava-preconditions) +- [Introduction to Guava Memoizer](https://www.baeldung.com/guava-memoizer) +- [Guava Functional Cookbook](https://www.baeldung.com/guava-functions-predicates) diff --git a/guava-2/pom.xml b/guava-modules/guava-core/pom.xml similarity index 89% rename from guava-2/pom.xml rename to guava-modules/guava-core/pom.xml index b19f59a9b4..5224148cb8 100644 --- a/guava-2/pom.xml +++ b/guava-modules/guava-core/pom.xml @@ -4,15 +4,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - guava-2 + guava-core 0.1.0-SNAPSHOT - guava-2 + guava-core com.baeldung - parent-java + guava-modules 0.0.1-SNAPSHOT - ../parent-java + ../ diff --git a/guava/src/main/java/com/baeldung/guava/memoizer/CostlySupplier.java b/guava-modules/guava-core/src/main/java/com/baeldung/guava/memoizer/CostlySupplier.java similarity index 100% rename from guava/src/main/java/com/baeldung/guava/memoizer/CostlySupplier.java rename to guava-modules/guava-core/src/main/java/com/baeldung/guava/memoizer/CostlySupplier.java diff --git a/guava/src/main/java/com/baeldung/guava/memoizer/Factorial.java b/guava-modules/guava-core/src/main/java/com/baeldung/guava/memoizer/Factorial.java similarity index 100% rename from guava/src/main/java/com/baeldung/guava/memoizer/Factorial.java rename to guava-modules/guava-core/src/main/java/com/baeldung/guava/memoizer/Factorial.java diff --git a/guava/src/main/java/com/baeldung/guava/memoizer/FibonacciSequence.java b/guava-modules/guava-core/src/main/java/com/baeldung/guava/memoizer/FibonacciSequence.java similarity index 100% rename from guava/src/main/java/com/baeldung/guava/memoizer/FibonacciSequence.java rename to guava-modules/guava-core/src/main/java/com/baeldung/guava/memoizer/FibonacciSequence.java diff --git a/guava-2/src/test/java/com/baeldung/guava/charmatcher/GuavaCharMatcherUnitTest.java b/guava-modules/guava-core/src/test/java/com/baeldung/guava/charmatcher/GuavaCharMatcherUnitTest.java similarity index 100% rename from guava-2/src/test/java/com/baeldung/guava/charmatcher/GuavaCharMatcherUnitTest.java rename to guava-modules/guava-core/src/test/java/com/baeldung/guava/charmatcher/GuavaCharMatcherUnitTest.java diff --git a/guava/src/test/java/com/baeldung/guava/GuavaFunctionalExamplesUnitTest.java b/guava-modules/guava-core/src/test/java/com/baeldung/guava/functional/GuavaFunctionalExamplesUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaFunctionalExamplesUnitTest.java rename to guava-modules/guava-core/src/test/java/com/baeldung/guava/functional/GuavaFunctionalExamplesUnitTest.java index b54a7c951a..0177f4f13e 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaFunctionalExamplesUnitTest.java +++ b/guava-modules/guava-core/src/test/java/com/baeldung/guava/functional/GuavaFunctionalExamplesUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.functional; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaMemoizerUnitTest.java b/guava-modules/guava-core/src/test/java/com/baeldung/guava/memoizer/GuavaMemoizerUnitTest.java similarity index 98% rename from guava/src/test/java/com/baeldung/guava/GuavaMemoizerUnitTest.java rename to guava-modules/guava-core/src/test/java/com/baeldung/guava/memoizer/GuavaMemoizerUnitTest.java index 9bafb7ad3f..9af9462e56 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaMemoizerUnitTest.java +++ b/guava-modules/guava-core/src/test/java/com/baeldung/guava/memoizer/GuavaMemoizerUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.memoizer; import com.google.common.base.Suppliers; import com.baeldung.guava.memoizer.CostlySupplier; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaPreConditionsUnitTest.java b/guava-modules/guava-core/src/test/java/com/baeldung/guava/preconditions/GuavaPreConditionsUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaPreConditionsUnitTest.java rename to guava-modules/guava-core/src/test/java/com/baeldung/guava/preconditions/GuavaPreConditionsUnitTest.java index fe3be9abf0..1f7111b12f 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaPreConditionsUnitTest.java +++ b/guava-modules/guava-core/src/test/java/com/baeldung/guava/preconditions/GuavaPreConditionsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.preconditions; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Arrays; diff --git a/guava-2/src/test/java/com/baeldung/guava/throwables/ThrowablesUnitTest.java b/guava-modules/guava-core/src/test/java/com/baeldung/guava/throwables/ThrowablesUnitTest.java similarity index 100% rename from guava-2/src/test/java/com/baeldung/guava/throwables/ThrowablesUnitTest.java rename to guava-modules/guava-core/src/test/java/com/baeldung/guava/throwables/ThrowablesUnitTest.java diff --git a/guava-collections-set/.gitignore b/guava-modules/guava-core/src/test/resources/.gitignore similarity index 100% rename from guava-collections-set/.gitignore rename to guava-modules/guava-core/src/test/resources/.gitignore diff --git a/guava-collections/src/test/resources/test.out b/guava-modules/guava-core/src/test/resources/test.out similarity index 100% rename from guava-collections/src/test/resources/test.out rename to guava-modules/guava-core/src/test/resources/test.out diff --git a/guava-collections/src/test/resources/test1.in b/guava-modules/guava-core/src/test/resources/test1.in similarity index 100% rename from guava-collections/src/test/resources/test1.in rename to guava-modules/guava-core/src/test/resources/test1.in diff --git a/guava-collections/src/test/resources/test1_1.in b/guava-modules/guava-core/src/test/resources/test1_1.in similarity index 100% rename from guava-collections/src/test/resources/test1_1.in rename to guava-modules/guava-core/src/test/resources/test1_1.in diff --git a/guava-collections/src/test/resources/test2.in b/guava-modules/guava-core/src/test/resources/test2.in similarity index 100% rename from guava-collections/src/test/resources/test2.in rename to guava-modules/guava-core/src/test/resources/test2.in diff --git a/guava-collections/src/test/resources/test_copy.in b/guava-modules/guava-core/src/test/resources/test_copy.in similarity index 100% rename from guava-collections/src/test/resources/test_copy.in rename to guava-modules/guava-core/src/test/resources/test_copy.in diff --git a/guava-collections/src/test/resources/test_le.txt b/guava-modules/guava-core/src/test/resources/test_le.txt similarity index 100% rename from guava-collections/src/test/resources/test_le.txt rename to guava-modules/guava-core/src/test/resources/test_le.txt diff --git a/guava-io/README.md b/guava-modules/guava-io/README.md similarity index 100% rename from guava-io/README.md rename to guava-modules/guava-io/README.md diff --git a/guava-io/pom.xml b/guava-modules/guava-io/pom.xml similarity index 94% rename from guava-io/pom.xml rename to guava-modules/guava-io/pom.xml index e01f76e2e3..6b3280755c 100644 --- a/guava-io/pom.xml +++ b/guava-modules/guava-io/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-java + guava-modules 0.0.1-SNAPSHOT - ../parent-java + ../ diff --git a/guava-io/src/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java b/guava-modules/guava-io/src/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java similarity index 100% rename from guava-io/src/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java rename to guava-modules/guava-io/src/test/java/com/baeldung/guava/GuavaCountingOutputStreamUnitTest.java diff --git a/guava-io/src/test/java/com/baeldung/guava/GuavaIOUnitTest.java b/guava-modules/guava-io/src/test/java/com/baeldung/guava/GuavaIOUnitTest.java similarity index 100% rename from guava-io/src/test/java/com/baeldung/guava/GuavaIOUnitTest.java rename to guava-modules/guava-io/src/test/java/com/baeldung/guava/GuavaIOUnitTest.java diff --git a/guava-io/src/test/resources/test1.in b/guava-modules/guava-io/src/test/resources/test1.in similarity index 100% rename from guava-io/src/test/resources/test1.in rename to guava-modules/guava-io/src/test/resources/test1.in diff --git a/guava-io/src/test/resources/test1_1.in b/guava-modules/guava-io/src/test/resources/test1_1.in similarity index 100% rename from guava-io/src/test/resources/test1_1.in rename to guava-modules/guava-io/src/test/resources/test1_1.in diff --git a/guava-io/src/test/resources/test2.in b/guava-modules/guava-io/src/test/resources/test2.in similarity index 100% rename from guava-io/src/test/resources/test2.in rename to guava-modules/guava-io/src/test/resources/test2.in diff --git a/guava/.gitignore b/guava-modules/guava-utilities/.gitignore similarity index 100% rename from guava/.gitignore rename to guava-modules/guava-utilities/.gitignore diff --git a/guava/README.md b/guava-modules/guava-utilities/README.md similarity index 60% rename from guava/README.md rename to guava-modules/guava-utilities/README.md index 24beca60c3..e2caa1a145 100644 --- a/guava/README.md +++ b/guava-modules/guava-utilities/README.md @@ -1,17 +1,12 @@ -## Guava +## Guava Utilities -This module contains articles a Google Guava +This module contains articles about utilities provided by Google Guava ### Relevant Articles: - -- [Guava Functional Cookbook](https://www.baeldung.com/guava-functions-predicates) -- [Guide to Guava’s PreConditions](https://www.baeldung.com/guava-preconditions) - [Introduction to Guava CacheLoader](https://www.baeldung.com/guava-cacheloader) -- [Introduction to Guava Memoizer](https://www.baeldung.com/guava-memoizer) - [Guide to Guava’s EventBus](https://www.baeldung.com/guava-eventbus) - [Guide to Guava’s Reflection Utilities](https://www.baeldung.com/guava-reflection) - [Guide to Mathematical Utilities in Guava](https://www.baeldung.com/guava-math) - [Bloom Filter in Java using Guava](https://www.baeldung.com/guava-bloom-filter) - [Quick Guide to the Guava RateLimiter](https://www.baeldung.com/guava-rate-limiter) - [Guava Cache](https://www.baeldung.com/guava-cache) -- [Introduction to Guava Throwables](https://www.baeldung.com/guava-throwables) diff --git a/guava/pom.xml b/guava-modules/guava-utilities/pom.xml similarity index 92% rename from guava/pom.xml rename to guava-modules/guava-utilities/pom.xml index 2c4ff07c84..0496f5b2e8 100644 --- a/guava/pom.xml +++ b/guava-modules/guava-utilities/pom.xml @@ -4,15 +4,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - guava + guava-utilities 0.1.0-SNAPSHOT - guava + guava-utilities com.baeldung - parent-java + guava-modules 0.0.1-SNAPSHOT - ../parent-java + ../ diff --git a/guava/src/main/java/com/baeldung/guava/CustomEvent.java b/guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus/CustomEvent.java similarity index 87% rename from guava/src/main/java/com/baeldung/guava/CustomEvent.java rename to guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus/CustomEvent.java index a154790374..55112b5cb3 100644 --- a/guava/src/main/java/com/baeldung/guava/CustomEvent.java +++ b/guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus/CustomEvent.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.eventbus; public class CustomEvent { private String action; diff --git a/guava/src/main/java/com/baeldung/guava/EventListener.java b/guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus/EventListener.java similarity index 96% rename from guava/src/main/java/com/baeldung/guava/EventListener.java rename to guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus/EventListener.java index 7bcfbcb8e9..404501b578 100644 --- a/guava/src/main/java/com/baeldung/guava/EventListener.java +++ b/guava-modules/guava-utilities/src/main/java/com/baeldung/guava/eventbus/EventListener.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.eventbus; import com.google.common.eventbus.DeadEvent; import com.google.common.eventbus.Subscribe; diff --git a/guava-modules/guava-utilities/src/main/resources/logback.xml b/guava-modules/guava-utilities/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/guava-modules/guava-utilities/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/guava/src/test/java/com/baeldung/guava/BloomFilterUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/bloomfilter/BloomFilterUnitTest.java similarity index 97% rename from guava/src/test/java/com/baeldung/guava/BloomFilterUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/bloomfilter/BloomFilterUnitTest.java index c11bf27256..96cc8ac1d9 100644 --- a/guava/src/test/java/com/baeldung/guava/BloomFilterUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/bloomfilter/BloomFilterUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.bloomfilter; import com.google.common.hash.BloomFilter; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaCacheUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cache/GuavaCacheUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaCacheUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cache/GuavaCacheUnitTest.java index 8aa56c7c52..0129d661fc 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaCacheUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cache/GuavaCacheUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.cache; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaCacheLoaderUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cacheloader/GuavaCacheLoaderUnitTest.java similarity index 98% rename from guava/src/test/java/com/baeldung/guava/GuavaCacheLoaderUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cacheloader/GuavaCacheLoaderUnitTest.java index bf9747ec18..7157c76494 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaCacheLoaderUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/cacheloader/GuavaCacheLoaderUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.cacheloader; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaEventBusUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/eventbus/GuavaEventBusUnitTest.java similarity index 90% rename from guava/src/test/java/com/baeldung/guava/GuavaEventBusUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/eventbus/GuavaEventBusUnitTest.java index bb9d26fcce..a6967d18f7 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaEventBusUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/eventbus/GuavaEventBusUnitTest.java @@ -1,5 +1,7 @@ -package com.baeldung.guava; +package com.baeldung.guava.eventbus; +import com.baeldung.guava.eventbus.CustomEvent; +import com.baeldung.guava.eventbus.EventListener; import com.google.common.eventbus.EventBus; import org.junit.After; import org.junit.Before; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaBigIntegerMathUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaBigIntegerMathUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaBigIntegerMathUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaBigIntegerMathUnitTest.java index cca42a688f..d890ef0bf0 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaBigIntegerMathUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaBigIntegerMathUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.mathutils; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaDoubleMathUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaDoubleMathUnitTest.java similarity index 98% rename from guava/src/test/java/com/baeldung/guava/GuavaDoubleMathUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaDoubleMathUnitTest.java index 9c78fb36fa..05a70e3654 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaDoubleMathUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaDoubleMathUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.mathutils; import static org.junit.Assert.*; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaIntMathUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaIntMathUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaIntMathUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaIntMathUnitTest.java index 547f423396..4ac3c93518 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaIntMathUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaIntMathUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.mathutils; import static org.junit.Assert.*; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaLongMathUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaLongMathUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaLongMathUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaLongMathUnitTest.java index 33c28d4594..41358b081b 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaLongMathUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaLongMathUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.mathutils; import static org.junit.Assert.*; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaMathUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaMathUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaMathUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaMathUnitTest.java index fce0fec13b..0d21a6f4ae 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaMathUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/mathutils/GuavaMathUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.mathutils; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.*; diff --git a/guava/src/test/java/com/baeldung/guava/RateLimiterLongRunningUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/ratelimiter/RateLimiterLongRunningUnitTest.java similarity index 98% rename from guava/src/test/java/com/baeldung/guava/RateLimiterLongRunningUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/ratelimiter/RateLimiterLongRunningUnitTest.java index 7372e9f6e9..cb06e6ff85 100644 --- a/guava/src/test/java/com/baeldung/guava/RateLimiterLongRunningUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/ratelimiter/RateLimiterLongRunningUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.ratelimiter; import com.google.common.util.concurrent.RateLimiter; diff --git a/guava/src/test/java/com/baeldung/guava/GuavaReflectionUtilsUnitTest.java b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/reflectionutils/GuavaReflectionUtilsUnitTest.java similarity index 99% rename from guava/src/test/java/com/baeldung/guava/GuavaReflectionUtilsUnitTest.java rename to guava-modules/guava-utilities/src/test/java/com/baeldung/guava/reflectionutils/GuavaReflectionUtilsUnitTest.java index 36df241711..8060191bdc 100644 --- a/guava/src/test/java/com/baeldung/guava/GuavaReflectionUtilsUnitTest.java +++ b/guava-modules/guava-utilities/src/test/java/com/baeldung/guava/reflectionutils/GuavaReflectionUtilsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.guava; +package com.baeldung.guava.reflectionutils; import com.google.common.collect.Lists; diff --git a/guava/src/test/resources/.gitignore b/guava-modules/guava-utilities/src/test/resources/.gitignore similarity index 100% rename from guava/src/test/resources/.gitignore rename to guava-modules/guava-utilities/src/test/resources/.gitignore diff --git a/guava/src/test/resources/test.out b/guava-modules/guava-utilities/src/test/resources/test.out similarity index 100% rename from guava/src/test/resources/test.out rename to guava-modules/guava-utilities/src/test/resources/test.out diff --git a/guava/src/test/resources/test1.in b/guava-modules/guava-utilities/src/test/resources/test1.in similarity index 100% rename from guava/src/test/resources/test1.in rename to guava-modules/guava-utilities/src/test/resources/test1.in diff --git a/guava/src/test/resources/test1_1.in b/guava-modules/guava-utilities/src/test/resources/test1_1.in similarity index 100% rename from guava/src/test/resources/test1_1.in rename to guava-modules/guava-utilities/src/test/resources/test1_1.in diff --git a/guava/src/test/resources/test2.in b/guava-modules/guava-utilities/src/test/resources/test2.in similarity index 100% rename from guava/src/test/resources/test2.in rename to guava-modules/guava-utilities/src/test/resources/test2.in diff --git a/guava/src/test/resources/test_copy.in b/guava-modules/guava-utilities/src/test/resources/test_copy.in similarity index 100% rename from guava/src/test/resources/test_copy.in rename to guava-modules/guava-utilities/src/test/resources/test_copy.in diff --git a/guava/src/test/resources/test_le.txt b/guava-modules/guava-utilities/src/test/resources/test_le.txt similarity index 100% rename from guava/src/test/resources/test_le.txt rename to guava-modules/guava-utilities/src/test/resources/test_le.txt diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index d1a2bbc16e..2d0bf68183 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -17,9 +17,16 @@ + guava-utilities + guava-core guava-18 guava-19 guava-21 + guava-collections + guava-collections-list + guava-collections-map + guava-collections-set + guava-io diff --git a/pom.xml b/pom.xml index 9d9c448887..5ed3791760 100644 --- a/pom.xml +++ b/pom.xml @@ -415,13 +415,7 @@ graphql/graphql-java grpc - gson - guava - guava-2 - guava-collections - guava-collections-map - guava-collections-set - guava-io + gson guava-modules guice @@ -933,12 +927,7 @@ graphql/graphql-java grpc - gson - guava - guava-collections - guava-collections-map - guava-collections-set - guava-io + gson guava-modules guice From a0bfc4c72a95983736c8bbf226bfa22ae24795a3 Mon Sep 17 00:00:00 2001 From: STS Date: Tue, 28 Jul 2020 14:23:08 +0200 Subject: [PATCH 095/155] change address --- .../com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java b/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java index b3f6949216..fa5baa37fa 100644 --- a/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java +++ b/apache-poi/src/test/java/com/baeldung/poi/excel/setformula/ExcelFormulaUnitTest.java @@ -14,7 +14,7 @@ import java.net.URISyntaxException; import java.nio.file.Paths; class ExcelFormulaUnitTest { - private static String FILE_NAME = "com/bealdung/poi/excel/setformula/SetFormulaTest.xlsx"; + private static String FILE_NAME = "com/baeldung/poi/excel/setformula/SetFormulaTest.xlsx"; private String fileLocation; private ExcelFormula excelFormula; From 45be1b60457eaa89e2dca7bbbc928154a2596a40 Mon Sep 17 00:00:00 2001 From: joe zhang Date: Tue, 28 Jul 2020 21:12:15 +0800 Subject: [PATCH 096/155] Add primitive type check method and unit tests --- .../core-java-lang-oop-types/pom.xml | 8 ++++ .../primitivetype/PrimitiveTypeUtil.java | 38 +++++++++++++++++ .../primitivetype/PrimitiveTypeUtilTest.java | 41 +++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java create mode 100644 core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java diff --git a/core-java-modules/core-java-lang-oop-types/pom.xml b/core-java-modules/core-java-lang-oop-types/pom.xml index 5555df4818..ee167bbae2 100644 --- a/core-java-modules/core-java-lang-oop-types/pom.xml +++ b/core-java-modules/core-java-lang-oop-types/pom.xml @@ -12,4 +12,12 @@ core-java-lang-oop-types core-java-lang-oop-types jar + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java new file mode 100644 index 0000000000..c749ed9dcd --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java @@ -0,0 +1,38 @@ +package com.baeldung.primitivetype; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.ClassUtils; + +import com.google.common.primitives.Primitives; + +public class PrimitiveTypeUtil { + + private static final Map, Class> WRAPPER_TYPE_MAP; + static { + WRAPPER_TYPE_MAP = new HashMap, Class>(16); + WRAPPER_TYPE_MAP.put(Integer.class, int.class); + WRAPPER_TYPE_MAP.put(Byte.class, byte.class); + WRAPPER_TYPE_MAP.put(Character.class, char.class); + WRAPPER_TYPE_MAP.put(Boolean.class, boolean.class); + WRAPPER_TYPE_MAP.put(Double.class, double.class); + WRAPPER_TYPE_MAP.put(Float.class, float.class); + WRAPPER_TYPE_MAP.put(Long.class, long.class); + WRAPPER_TYPE_MAP.put(Short.class, short.class); + WRAPPER_TYPE_MAP.put(Void.class, void.class); + } + + public boolean isPrimitiveTypeByCommansLang(Object source) { + return ClassUtils.isPrimitiveOrWrapper(source.getClass()); + } + + public boolean isPrimitiveTypeByGuava(Object source) { + return Primitives.isWrapperType(source.getClass()); + } + + public boolean isPrimitiveType(Object source) { + return WRAPPER_TYPE_MAP.containsKey(source.getClass()); + } + +} diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java new file mode 100644 index 0000000000..7d3c2964d4 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java @@ -0,0 +1,41 @@ +package com.baeldung.primitivetype; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class PrimitiveTypeUtilTest { + + private PrimitiveTypeUtil primitiveTypeUtil; + private boolean booleanVal = false; + private Long longWrapper = 1L; + private String nonPrimitiveVal = "Test"; + + @Before + public void setup() { + primitiveTypeUtil = new PrimitiveTypeUtil(); + } + + @Test + public void givenObjectWhenCheckWithGuavaShouldValidate() { + assertTrue(primitiveTypeUtil.isPrimitiveTypeByGuava(booleanVal)); + assertTrue(primitiveTypeUtil.isPrimitiveTypeByGuava(longWrapper)); + assertFalse(primitiveTypeUtil.isPrimitiveTypeByGuava(nonPrimitiveVal)); + } + + @Test + public void givenObjectWhenCheckWithCommansLangShouldValidate() { + assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommansLang(booleanVal)); + assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommansLang(longWrapper)); + assertFalse(primitiveTypeUtil.isPrimitiveTypeByCommansLang(nonPrimitiveVal)); + } + + @Test + public void givenPrimitiveOrWrapperWhenCheckWithCustomMethodShouldReturnTrue() { + assertTrue(primitiveTypeUtil.isPrimitiveType(booleanVal)); + assertTrue(primitiveTypeUtil.isPrimitiveType(longWrapper)); + assertFalse(primitiveTypeUtil.isPrimitiveType(nonPrimitiveVal)); + } +} From 011b56d158f8bfa4b9bfc34e3e7a90975e5491b9 Mon Sep 17 00:00:00 2001 From: STS Date: Tue, 28 Jul 2020 20:17:02 +0200 Subject: [PATCH 097/155] Trigger Test From 92b315a3a6cf07165f5f9e0e96eff1c22ba52c59 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Tue, 28 Jul 2020 22:08:52 +0200 Subject: [PATCH 098/155] BAEL-3905: Mark test ctx as dirty after each test method (#9784) --- .../com/baeldung/testloglevel/TestLogLevelApplication.java | 4 +--- .../LogbackMultiProfileTestLogLevelIntegrationTest.java | 4 ++-- .../testloglevel/LogbackTestLogLevelIntegrationTest.java | 4 ++-- .../testloglevel/TestLogLevelWithProfileIntegrationTest.java | 4 ++-- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java index ed8218c6a3..ef4534938b 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/testloglevel/TestLogLevelApplication.java @@ -3,13 +3,11 @@ package com.baeldung.testloglevel; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import com.baeldung.boot.Application; - @SpringBootApplication(scanBasePackages = {"com.baeldung.testloglevel", "com.baeldung.component"}) public class TestLogLevelApplication { public static void main(String[] args) { - SpringApplication.run(Application.class, args); + SpringApplication.run(TestLogLevelApplication.class, args); } } diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java index f8bd61e5c7..ffe99672be 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackMultiProfileTestLogLevelIntegrationTest.java @@ -16,9 +16,9 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; -@DirtiesContext(classMode = AFTER_CLASS) +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java index ffe9d400ed..cbd22e8087 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/LogbackTestLogLevelIntegrationTest.java @@ -16,9 +16,9 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; -@DirtiesContext(classMode = AFTER_CLASS) +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java index 6e80f50c00..571b826b80 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/testloglevel/TestLogLevelWithProfileIntegrationTest.java @@ -16,10 +16,10 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS; +import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @RunWith(SpringRunner.class) -@DirtiesContext(classMode = AFTER_CLASS) +@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) @ActiveProfiles("logging-test") From 12322ff46b265ccf3b58aac62c5d197bc495bda4 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Wed, 29 Jul 2020 08:59:06 +0200 Subject: [PATCH 099/155] update test --- .../java/com/baeldung/screenshot/ScreenshotTest.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java index 3df31897e1..20d2d333a3 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java @@ -17,10 +17,9 @@ public class ScreenshotTest { public void takeScreenshotOfMainScreen() throws Exception { Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage capture = new Robot().createScreenCapture(screenRect); - File imageFile = new File("single-screen.bmp"); + File imageFile = File.createTempFile("single-screen", "bmp"); ImageIO.write(capture, "bmp", imageFile); assertTrue(imageFile.exists()); - imageFile.delete(); } @Test @@ -34,10 +33,9 @@ public class ScreenshotTest { allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height); } BufferedImage capture = new Robot().createScreenCapture(allScreenBounds); - File imageFile = new File("all-screens.bmp"); + File imageFile = File.createTempFile("all-screens", "bmp"); ImageIO.write(capture, "bmp", imageFile); assertTrue(imageFile.exists()); - imageFile.delete(); } @Test @@ -45,10 +43,9 @@ public class ScreenshotTest { Rectangle componentRect = component.getBounds(); BufferedImage bufferedImage = new BufferedImage(componentRect.width, componentRect.height, BufferedImage.TYPE_INT_ARGB); component.paint(bufferedImage.getGraphics()); - File imageFile = new File("component-screenshot.bmp"); + File imageFile = File.createTempFile("component-screenshot", "bmp"); ImageIO.write(bufferedImage, "bmp", imageFile); assertTrue(imageFile.exists()); - imageFile.delete(); } } \ No newline at end of file From 768658cfc8ab0ad9a9df6fca9574f72ac1905576 Mon Sep 17 00:00:00 2001 From: helga_sh Date: Wed, 29 Jul 2020 11:36:09 +0300 Subject: [PATCH 100/155] Fixed builder formatting --- .../baeldung/deeplearning4j/cnn/CnnModel.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java index bd87709c0e..efa7f828ed 100644 --- a/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java +++ b/deeplearning4j/src/main/java/com/baeldung/deeplearning4j/cnn/CnnModel.java @@ -30,23 +30,23 @@ class CnnModel { this.properties = properties; MultiLayerConfiguration configuration = new NeuralNetConfiguration.Builder() - .seed(1611) - .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) - .learningRate(properties.getLearningRate()) - .regularization(true) - .updater(properties.getOptimizer()) - .list() - .layer(0, conv5x5()) - .layer(1, pooling2x2Stride2()) - .layer(2, conv3x3Stride1Padding2()) - .layer(3, pooling2x2Stride1()) - .layer(4, conv3x3Stride1Padding1()) - .layer(5, pooling2x2Stride1()) - .layer(6, dense()) - .pretrain(false) - .backprop(true) - .setInputType(dataSetService.inputType()) - .build(); + .seed(1611) + .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) + .learningRate(properties.getLearningRate()) + .regularization(true) + .updater(properties.getOptimizer()) + .list() + .layer(0, conv5x5()) + .layer(1, pooling2x2Stride2()) + .layer(2, conv3x3Stride1Padding2()) + .layer(3, pooling2x2Stride1()) + .layer(4, conv3x3Stride1Padding1()) + .layer(5, pooling2x2Stride1()) + .layer(6, dense()) + .pretrain(false) + .backprop(true) + .setInputType(dataSetService.inputType()) + .build(); network = new MultiLayerNetwork(configuration); } From a4b9016d6cbdea0b74d1754fbcabf8c5b988d5b5 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Thu, 30 Jul 2020 08:23:43 +0530 Subject: [PATCH 101/155] JAVA-2154: Added guava dependency to module pom directly (#9789) instead of inheriting from parent --- guava-modules/pom.xml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index 2d0bf68183..b625f9fd0f 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -4,9 +4,6 @@ 4.0.0 guava-modules guava-modules - - 5.6.2 - pom @@ -30,6 +27,11 @@ + + com.google.guava + guava + ${guava.version} + org.junit.jupiter junit-jupiter @@ -54,4 +56,9 @@ + + 5.6.2 + 29.0-jre + + From 6889e238ff978ab3ed3175b011bcc0309fccc60d Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 30 Jul 2020 07:50:21 +0200 Subject: [PATCH 102/155] BAEL-3415: Get rid of the MockitoAnnotations.initMocks (#9787) --- .../fluentapi/PizzaServiceUnitTest.java | 29 ++++++++----------- .../ArgumentMatcherWithLambdaUnitTest.java | 25 +++++++--------- .../ArgumentMatcherWithoutLambdaUnitTest.java | 14 ++++----- .../java8/CustomAnswerWithLambdaUnitTest.java | 6 ++-- .../CustomAnswerWithoutLambdaUnitTest.java | 7 ++--- .../mockito/java8/JobServiceUnitTest.java | 22 ++++++-------- .../UnemploymentServiceImplUnitTest.java | 24 +++++++-------- .../MockitoUnecessaryStubUnitTest.java | 28 ++++++++---------- 8 files changed, 66 insertions(+), 89 deletions(-) diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/fluentapi/PizzaServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/fluentapi/PizzaServiceUnitTest.java index b5dd10b1d4..5993d1968c 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/fluentapi/PizzaServiceUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/fluentapi/PizzaServiceUnitTest.java @@ -1,5 +1,16 @@ package com.baeldung.mockito.fluentapi; +import com.baeldung.mockito.fluentapi.Pizza.PizzaBuilder; +import com.baeldung.mockito.fluentapi.Pizza.PizzaSize; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Answers; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -8,18 +19,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Answers; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -import com.baeldung.mockito.fluentapi.Pizza.PizzaBuilder; -import com.baeldung.mockito.fluentapi.Pizza.PizzaSize; - +@RunWith(MockitoJUnitRunner.class) public class PizzaServiceUnitTest { @Mock @@ -33,11 +33,6 @@ public class PizzaServiceUnitTest { @Captor private ArgumentCaptor sizeCaptor; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - @Test public void givenTraditonalMocking_whenServiceInvoked_thenPizzaIsBuilt() { PizzaBuilder nameBuilder = Mockito.mock(Pizza.PizzaBuilder.class); diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java index 2efac513b7..8d6d4bade1 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithLambdaUnitTest.java @@ -1,19 +1,19 @@ package com.baeldung.mockito.java8; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatchers; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - - +@RunWith(MockitoJUnitRunner.class) public class ArgumentMatcherWithLambdaUnitTest { @InjectMocks @@ -36,9 +36,4 @@ public class ArgumentMatcherWithLambdaUnitTest { assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(linda)); assertFalse(unemploymentService.personIsEntitledToUnemploymentSupport(peter)); } - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - } } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java index aaa8d03585..3b003d0a87 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/ArgumentMatcherWithoutLambdaUnitTest.java @@ -1,8 +1,12 @@ package com.baeldung.mockito.java8; -import org.junit.Before; import org.junit.Test; -import org.mockito.*; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import java.util.Optional; @@ -11,6 +15,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; +@RunWith(MockitoJUnitRunner.class) public class ArgumentMatcherWithoutLambdaUnitTest { private class PeterArgumentMatcher implements ArgumentMatcher { @@ -43,9 +48,4 @@ public class ArgumentMatcherWithoutLambdaUnitTest { assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(linda)); assertFalse(unemploymentService.personIsEntitledToUnemploymentSupport(peter)); } - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - } } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java index 06e9bca6d3..8886d1325c 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithLambdaUnitTest.java @@ -2,9 +2,10 @@ package com.baeldung.mockito.java8; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import java.util.stream.Stream; @@ -13,6 +14,7 @@ import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; +@RunWith(MockitoJUnitRunner.class) public class CustomAnswerWithLambdaUnitTest { @InjectMocks @@ -37,8 +39,6 @@ public class CustomAnswerWithLambdaUnitTest { @Before public void init() { - MockitoAnnotations.initMocks(this); - when(jobService.listJobs(any(Person.class))).then((i) -> Stream.of(new JobPosition("Teacher")) .filter(p -> ((Person) i.getArgument(0)).getName().equals("Peter"))); diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java index d5b9d6d1ce..f75a62fea5 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/CustomAnswerWithoutLambdaUnitTest.java @@ -2,10 +2,11 @@ package com.baeldung.mockito.java8; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import java.util.stream.Stream; @@ -15,7 +16,7 @@ import static org.junit.Assert.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; - +@RunWith(MockitoJUnitRunner.class) public class CustomAnswerWithoutLambdaUnitTest { private class PersonAnswer implements Answer> { @@ -54,8 +55,6 @@ public class CustomAnswerWithoutLambdaUnitTest { @Before public void init() { - MockitoAnnotations.initMocks(this); - when(jobService.listJobs(any(Person.class))).then(new PersonAnswer()); } } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java index 9ea5c1db47..5b3bc5e3d5 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/JobServiceUnitTest.java @@ -1,18 +1,19 @@ package com.baeldung.mockito.java8; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.when; -import java.util.Optional; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - +@RunWith(MockitoJUnitRunner.class) public class JobServiceUnitTest { @Mock private JobService jobService; @@ -36,9 +37,4 @@ public class JobServiceUnitTest { assertTrue(jobService.assignJobPosition(person, new JobPosition())); } - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - } } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java index b3b71e5bf9..87093fc1ba 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/java8/UnemploymentServiceImplUnitTest.java @@ -1,19 +1,20 @@ package com.baeldung.mockito.java8; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Optional; +import java.util.stream.Stream; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; -import java.util.Optional; -import java.util.stream.Stream; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - +@RunWith(MockitoJUnitRunner.class) public class UnemploymentServiceImplUnitTest { @Mock private JobService jobService; @@ -54,9 +55,4 @@ public class UnemploymentServiceImplUnitTest { // This will fail when Mockito 1 is used assertFalse(unemploymentService.searchJob(person, "").isPresent()); } - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - } } diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/misusing/MockitoUnecessaryStubUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/misusing/MockitoUnecessaryStubUnitTest.java index 00edb699de..828d31f6f9 100644 --- a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/misusing/MockitoUnecessaryStubUnitTest.java +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/misusing/MockitoUnecessaryStubUnitTest.java @@ -1,21 +1,22 @@ package com.baeldung.mockito.misusing; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.exceptions.misusing.UnnecessaryStubbingException; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.quality.Strictness; + +import java.util.ArrayList; + import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; -import java.util.ArrayList; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.exceptions.misusing.UnnecessaryStubbingException; -import org.mockito.junit.MockitoJUnit; -import org.mockito.quality.Strictness; - +@RunWith(MockitoJUnitRunner.class) public class MockitoUnecessaryStubUnitTest { @Rule @@ -25,11 +26,6 @@ public class MockitoUnecessaryStubUnitTest { @Mock private ArrayList mockList; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - @Test public void givenUnusedStub_whenInvokingGetThenThrowUnnecessaryStubbingException() { rule.expectedFailure(UnnecessaryStubbingException.class); From a623d1714fa8611dd5e9d630ca6686290072f316 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 30 Jul 2020 07:57:02 +0200 Subject: [PATCH 103/155] BAEL-4468: Fix nullSafeSet method (#9791) --- .../com/baeldung/hibernate/customtypes/PhoneNumberType.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java index 9f09352bec..79caa3d6fd 100644 --- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java +++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/PhoneNumberType.java @@ -57,6 +57,8 @@ public class PhoneNumberType implements UserType { if (Objects.isNull(value)) { st.setNull(index, Types.INTEGER); + st.setNull(index+1, Types.INTEGER); + st.setNull(index+2, Types.INTEGER); } else { PhoneNumber employeeNumber = (PhoneNumber) value; st.setInt(index,employeeNumber.getCountryCode()); From baa46f6f4fb4ede1cb89893dacde69cbbf9baef1 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Thu, 30 Jul 2020 11:26:57 +0200 Subject: [PATCH 104/155] rename --- .../{ScreenshotTest.java => ScreenshotUnitTest.java} | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) rename core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/{ScreenshotTest.java => ScreenshotUnitTest.java} (85%) diff --git a/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java b/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotUnitTest.java similarity index 85% rename from core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java rename to core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotUnitTest.java index 20d2d333a3..6bd0e7dff7 100644 --- a/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotTest.java +++ b/core-java-modules/core-java-os/src/test/java/com/baeldung/screenshot/ScreenshotUnitTest.java @@ -11,10 +11,10 @@ import org.junit.Test; import static org.junit.Assert.assertTrue; -public class ScreenshotTest { +public class ScreenshotUnitTest { @Test - public void takeScreenshotOfMainScreen() throws Exception { + public void givenMainScreen_whenTakeScreenshot_thenSaveToFile() throws Exception { Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage capture = new Robot().createScreenCapture(screenRect); File imageFile = File.createTempFile("single-screen", "bmp"); @@ -23,7 +23,7 @@ public class ScreenshotTest { } @Test - public void takeScreenshotOfAllScreens() throws Exception { + public void givenMultipleScreens_whenTakeScreenshot_thenSaveToFile() throws Exception { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] screens = ge.getScreenDevices(); Rectangle allScreenBounds = new Rectangle(); @@ -39,7 +39,7 @@ public class ScreenshotTest { } @Test - public void makeScreenshot(Component component) throws Exception { + public void givenComponent_whenTakeScreenshot_thenSaveToFile(Component component) throws Exception { Rectangle componentRect = component.getBounds(); BufferedImage bufferedImage = new BufferedImage(componentRect.width, componentRect.height, BufferedImage.TYPE_INT_ARGB); component.paint(bufferedImage.getGraphics()); From 06ac0b5589d6ff198b10c5ff411e1f09d64a18bd Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 30 Jul 2020 18:06:42 +0530 Subject: [PATCH 105/155] JAVA-1525: Moved 1 article to security module --- spring-5-reactive-security/README.md | 1 + .../cors/annotated/CorsOnAnnotatedElementsApplication.java | 0 .../cors/annotated/controllers/CorsOnClassController.java | 0 .../cors/annotated/controllers/CorsOnMethodsController.java | 0 .../reactive/cors/global/CorsGlobalConfigApplication.java | 0 .../reactive/cors/global/config/CorsGlobalConfiguration.java | 0 .../cors/global/controllers/FurtherCorsConfigsController.java | 0 .../cors/global/controllers/RegularRestController.java | 0 .../functional/handlers/CorsGlobalFunctionalHandler.java | 0 .../cors/global/functional/routers/CorsRouterFunctions.java | 0 .../reactive/cors/webfilter/CorsWebFilterApplication.java | 0 .../reactive/cors/webfilter/config/CorsWebFilterConfig.java | 0 .../webfilter/controllers/FurtherCorsConfigsController.java | 0 .../cors/webfilter/controllers/RegularRestController.java | 0 .../functional/handlers/CorsWithWebFilterHandler.java | 0 .../functional/routers/CorsWithWebFilterRouterFunctions.java | 0 .../reactive/cors/CorsOnAnnotatedElementsLiveTest.java | 4 +++- .../baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java | 4 +++- .../com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java | 4 +++- 19 files changed, 10 insertions(+), 3 deletions(-) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java (100%) rename {spring-5-reactive => spring-5-reactive-security}/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java (96%) rename {spring-5-reactive => spring-5-reactive-security}/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java (94%) rename {spring-5-reactive => spring-5-reactive-security}/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java (94%) diff --git a/spring-5-reactive-security/README.md b/spring-5-reactive-security/README.md index a0f47a503d..915f74cd78 100644 --- a/spring-5-reactive-security/README.md +++ b/spring-5-reactive-security/README.md @@ -12,3 +12,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Guide to Spring 5 WebFlux](https://www.baeldung.com/spring-webflux) - [Introduction to the Functional Web Framework in Spring 5](https://www.baeldung.com/spring-5-functional-web) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) +- [Spring Webflux and CORS](https://www.baeldung.com/spring-webflux-cors) diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/annotated/CorsOnAnnotatedElementsApplication.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnClassController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/annotated/controllers/CorsOnMethodsController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/CorsGlobalConfigApplication.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/config/CorsGlobalConfiguration.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/controllers/FurtherCorsConfigsController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/controllers/RegularRestController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/functional/handlers/CorsGlobalFunctionalHandler.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/global/functional/routers/CorsRouterFunctions.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/CorsWebFilterApplication.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/config/CorsWebFilterConfig.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/FurtherCorsConfigsController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/controllers/RegularRestController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/functional/handlers/CorsWithWebFilterHandler.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java b/spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java rename to spring-5-reactive-security/src/main/java/com/baeldung/reactive/cors/webfilter/functional/routers/CorsWithWebFilterRouterFunctions.java diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java similarity index 96% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java index e6847e63da..5fd20eedfd 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnAnnotatedElementsLiveTest.java @@ -6,7 +6,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +import com.baeldung.reactive.cors.annotated.CorsOnAnnotatedElementsApplication; + +@SpringBootTest(classes = CorsOnAnnotatedElementsApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnAnnotatedElementsLiveTest { private static final String BASE_URL = "http://localhost:8081"; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java similarity index 94% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java index 008f1a16f2..5c6582c127 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnGlobalConfigLiveTest.java @@ -6,7 +6,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +import com.baeldung.reactive.cors.global.CorsGlobalConfigApplication; + +@SpringBootTest(classes = CorsGlobalConfigApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnGlobalConfigLiveTest { private static final String BASE_URL = "http://localhost:8082"; diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java similarity index 94% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java rename to spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java index f8a4f34e29..7cc44454ec 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java +++ b/spring-5-reactive-security/src/test/java/com/baeldung/reactive/cors/CorsOnWebFilterLiveTest.java @@ -6,7 +6,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +import com.baeldung.reactive.cors.webfilter.CorsWebFilterApplication; + +@SpringBootTest(classes = CorsWebFilterApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class CorsOnWebFilterLiveTest { private static final String BASE_URL = "http://localhost:8083"; From 4dc2535bc5361493c305a1834b7c6ad90210ef3c Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 30 Jul 2020 18:07:49 +0530 Subject: [PATCH 106/155] JAVA-1525: Moved 1 article to reactive-2 module --- .../serversentevents/consumer/ConsumerSSEApplication.java | 0 .../consumer/controller/ClientController.java | 0 .../serversentevents/server/ServerSSEApplication.java | 0 .../serversentevents/server/controllers/ServerController.java | 0 .../reactive/serversentsevents/ServiceSentEventLiveTest.java | 4 +++- 5 files changed, 3 insertions(+), 1 deletion(-) rename {spring-5-reactive => spring-5-reactive-2}/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java (100%) rename {spring-5-reactive => spring-5-reactive-2}/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java (100%) rename {spring-5-reactive => spring-5-reactive-2}/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java (100%) rename {spring-5-reactive => spring-5-reactive-2}/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java (100%) rename {spring-5-reactive => spring-5-reactive-2}/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java (92%) diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java b/spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java rename to spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/ConsumerSSEApplication.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java b/spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java rename to spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/consumer/controller/ClientController.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java b/spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java rename to spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/server/ServerSSEApplication.java diff --git a/spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java b/spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java similarity index 100% rename from spring-5-reactive/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java rename to spring-5-reactive-2/src/main/java/com/baeldung/reactive/serversentevents/server/controllers/ServerController.java diff --git a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java b/spring-5-reactive-2/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java similarity index 92% rename from spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java rename to spring-5-reactive-2/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java index 547cd99034..946a038763 100644 --- a/spring-5-reactive/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java +++ b/spring-5-reactive-2/src/test/java/com/baeldung/reactive/serversentsevents/ServiceSentEventLiveTest.java @@ -8,7 +8,9 @@ import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; -@SpringBootTest +import com.baeldung.reactive.serversentevents.server.ServerSSEApplication; + +@SpringBootTest(classes = ServerSSEApplication.class) @WithMockUser public class ServiceSentEventLiveTest { From efbd00fdde4246cd6ccf9b955f4cb59c511a6f37 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 30 Jul 2020 18:09:10 +0530 Subject: [PATCH 107/155] JAVA-1525: Moved 1 article to -client module to make space for 1 from reactive module --- spring-5-reactive-2/pom.xml | 5 +++++ spring-5-reactive-client/pom.xml | 4 ++++ .../java/com/baeldung/webclient/filter/WebClientFilters.java | 0 .../baeldung/webclient/filter/FilteredWebClientUnitTest.java | 0 4 files changed, 9 insertions(+) rename {spring-5-reactive-2 => spring-5-reactive-client}/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java (100%) rename {spring-5-reactive-2 => spring-5-reactive-client}/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java (100%) diff --git a/spring-5-reactive-2/pom.xml b/spring-5-reactive-2/pom.xml index fdeebd1dfd..4cb85d879e 100644 --- a/spring-5-reactive-2/pom.xml +++ b/spring-5-reactive-2/pom.xml @@ -53,6 +53,11 @@ reactor-test test + + org.springframework.security + spring-security-test + test + diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 0b5efd1a47..7ae7ba6edd 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -33,6 +33,10 @@ org.springframework.boot spring-boot-starter-webflux + + org.springframework.boot + spring-boot-starter-security + org.projectreactor reactor-spring diff --git a/spring-5-reactive-2/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java b/spring-5-reactive-client/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java similarity index 100% rename from spring-5-reactive-2/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java rename to spring-5-reactive-client/src/main/java/com/baeldung/webclient/filter/WebClientFilters.java diff --git a/spring-5-reactive-2/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java b/spring-5-reactive-client/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java similarity index 100% rename from spring-5-reactive-2/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java rename to spring-5-reactive-client/src/test/java/com/baeldung/webclient/filter/FilteredWebClientUnitTest.java From a788fa2751dbfbbdd93eca96551e494726174806 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 30 Jul 2020 18:09:51 +0530 Subject: [PATCH 108/155] JAVA-1525: README updates --- spring-5-reactive-2/README.md | 2 +- spring-5-reactive-client/README.md | 1 + spring-5-reactive/README.md | 3 --- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/spring-5-reactive-2/README.md b/spring-5-reactive-2/README.md index 061c15b148..54f7ad35b1 100644 --- a/spring-5-reactive-2/README.md +++ b/spring-5-reactive-2/README.md @@ -8,5 +8,5 @@ This module contains articles about reactive Spring 5 - [Testing Reactive Streams Using StepVerifier and TestPublisher](https://www.baeldung.com/reactive-streams-step-verifier-test-publisher) - [Debugging Reactive Streams in Spring 5](https://www.baeldung.com/spring-debugging-reactive-streams) - [Static Content in Spring WebFlux](https://www.baeldung.com/spring-webflux-static-content) -- [Spring WebClient Filters](https://www.baeldung.com/spring-webclient-filters) +- [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events) - More articles: [[<-- prev]](/spring-5-reactive) diff --git a/spring-5-reactive-client/README.md b/spring-5-reactive-client/README.md index bb308ae330..eebdc23aed 100644 --- a/spring-5-reactive-client/README.md +++ b/spring-5-reactive-client/README.md @@ -10,3 +10,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Simultaneous Spring WebClient Calls](https://www.baeldung.com/spring-webclient-simultaneous-calls) - [Logging Spring WebClient Calls](https://www.baeldung.com/spring-log-webclient-calls) - [Mocking a WebClient in Spring](https://www.baeldung.com/spring-mocking-webclient) +- [Spring WebClient Filters](https://www.baeldung.com/spring-webclient-filters) diff --git a/spring-5-reactive/README.md b/spring-5-reactive/README.md index 41d831632a..1945b7ea33 100644 --- a/spring-5-reactive/README.md +++ b/spring-5-reactive/README.md @@ -7,14 +7,11 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring ### Relevant Articles -- [Introduction to the Functional Web Framework in Spring 5](https://www.baeldung.com/spring-5-functional-web) - [Spring 5 WebClient](https://www.baeldung.com/spring-5-webclient) - [Exploring the Spring 5 WebFlux URL Matching](https://www.baeldung.com/spring-5-mvc-url-matching) - [Reactive WebSockets with Spring 5](https://www.baeldung.com/spring-5-reactive-websockets) - [Spring Webflux Filters](https://www.baeldung.com/spring-webflux-filters) - [How to Set a Header on a Response with Spring 5](https://www.baeldung.com/spring-response-header) -- [Spring Webflux and CORS](https://www.baeldung.com/spring-webflux-cors) - [Handling Errors in Spring WebFlux](https://www.baeldung.com/spring-webflux-errors) -- [Server-Sent Events in Spring](https://www.baeldung.com/spring-server-sent-events) - [A Guide to Spring Session Reactive Support: WebSession](https://www.baeldung.com/spring-session-reactive) - More articles: [[next -->]](/spring-5-reactive-2) From 1deeca3b47f97b31fc8cd0417175d840b9b9537c Mon Sep 17 00:00:00 2001 From: joe zhang Date: Thu, 30 Jul 2020 21:00:51 +0800 Subject: [PATCH 109/155] determine if an Object is of primitive type --- .../java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java index 7d3c2964d4..ff532520c2 100644 --- a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java @@ -11,7 +11,7 @@ public class PrimitiveTypeUtilTest { private PrimitiveTypeUtil primitiveTypeUtil; private boolean booleanVal = false; private Long longWrapper = 1L; - private String nonPrimitiveVal = "Test"; + private String nonPrimitiveVal = "non primitive string"; @Before public void setup() { From f29c757e18aff1a9da058768857bcfd3f24bf0ef Mon Sep 17 00:00:00 2001 From: joe zhang Date: Thu, 30 Jul 2020 21:09:33 +0800 Subject: [PATCH 110/155] determine if an Object is of primitive type --- .../java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java index ff532520c2..411bc422e5 100644 --- a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java @@ -26,7 +26,7 @@ public class PrimitiveTypeUtilTest { } @Test - public void givenObjectWhenCheckWithCommansLangShouldValidate() { + public void givenObjectWhenCheckWithCommonsLangShouldValidate() { assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommansLang(booleanVal)); assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommansLang(longWrapper)); assertFalse(primitiveTypeUtil.isPrimitiveTypeByCommansLang(nonPrimitiveVal)); From 6e43adc10748a9dcaf05acbe11ec0f6ca6961506 Mon Sep 17 00:00:00 2001 From: joe zhang Date: Thu, 30 Jul 2020 21:15:06 +0800 Subject: [PATCH 111/155] determine if an Object is of primitive type --- .../java/com/baeldung/primitivetype/PrimitiveTypeUtil.java | 2 +- .../com/baeldung/primitivetype/PrimitiveTypeUtilTest.java | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java index c749ed9dcd..1b2083b548 100644 --- a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java @@ -23,7 +23,7 @@ public class PrimitiveTypeUtil { WRAPPER_TYPE_MAP.put(Void.class, void.class); } - public boolean isPrimitiveTypeByCommansLang(Object source) { + public boolean isPrimitiveTypeByCommonsLang(Object source) { return ClassUtils.isPrimitiveOrWrapper(source.getClass()); } diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java index 411bc422e5..79b58967dd 100644 --- a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java @@ -27,9 +27,9 @@ public class PrimitiveTypeUtilTest { @Test public void givenObjectWhenCheckWithCommonsLangShouldValidate() { - assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommansLang(booleanVal)); - assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommansLang(longWrapper)); - assertFalse(primitiveTypeUtil.isPrimitiveTypeByCommansLang(nonPrimitiveVal)); + assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommonsLang(booleanVal)); + assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommonsLang(longWrapper)); + assertFalse(primitiveTypeUtil.isPrimitiveTypeByCommonsLang(nonPrimitiveVal)); } @Test From ae479954f48ae784e1c7e66a19b03e60cd0b31b7 Mon Sep 17 00:00:00 2001 From: joe zhang Date: Fri, 31 Jul 2020 00:33:26 +0800 Subject: [PATCH 112/155] refactor unit test name --- ...rimitiveTypeUtilTest.java => PrimitiveTypeUtilUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/{PrimitiveTypeUtilTest.java => PrimitiveTypeUtilUnitTest.java} (97%) diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java similarity index 97% rename from core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java rename to core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java index 79b58967dd..5cd1b9f9d7 100644 --- a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilTest.java +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java @@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; -public class PrimitiveTypeUtilTest { +public class PrimitiveTypeUtilUnitTest { private PrimitiveTypeUtil primitiveTypeUtil; private boolean booleanVal = false; From 79b9df98a2c588bc1270ca788bb48f0d802bafc6 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Thu, 30 Jul 2020 21:52:53 +0430 Subject: [PATCH 113/155] boolean[] vs. BitSet: Which is more efficient? --- jmh/pom.xml | 32 ++ .../java/com/baeldung/bitset/Plotter.java | 36 ++ .../main/java/com/baeldung/bitset/Sizing.java | 17 + .../bitset/VectorOfBitsBenchmark.java | 75 +++ jmh/src/main/resources/bitset/cardinal.csv | 449 ++++++++++++++++++ jmh/src/main/resources/bitset/get.csv | 449 ++++++++++++++++++ jmh/src/main/resources/bitset/set.csv | 449 ++++++++++++++++++ 7 files changed, 1507 insertions(+) create mode 100644 jmh/src/main/java/com/baeldung/bitset/Plotter.java create mode 100644 jmh/src/main/java/com/baeldung/bitset/Sizing.java create mode 100644 jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java create mode 100644 jmh/src/main/resources/bitset/cardinal.csv create mode 100644 jmh/src/main/resources/bitset/get.csv create mode 100644 jmh/src/main/resources/bitset/set.csv diff --git a/jmh/pom.xml b/jmh/pom.xml index 735198036e..16a5bc54a4 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -26,6 +26,11 @@ jmh-generator-annprocess ${openjdk.jmh.version} + + org.openjdk.jol + jol-core + ${jol-core.version} + @@ -42,12 +47,39 @@ + + + org.apache.maven.plugins + maven-assembly-plugin + ${maven-assembly-plugin.version} + + + jar-with-dependencies + + + + com.baeldung.BenchmarkRunner + + + + + + make-assembly + package + + single + + + + 1.19 3.0.2 + 0.10 + 3.2.0 \ No newline at end of file diff --git a/jmh/src/main/java/com/baeldung/bitset/Plotter.java b/jmh/src/main/java/com/baeldung/bitset/Plotter.java new file mode 100644 index 0000000000..beb136f515 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/bitset/Plotter.java @@ -0,0 +1,36 @@ +package com.baeldung.bitset; + +import org.openjdk.jol.info.ClassLayout; +import org.openjdk.jol.info.GraphLayout; + +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.BitSet; + +public class Plotter { + + public static void main(String[] args) throws IOException { + Path path = Paths.get("footprint.csv"); + try (BufferedWriter stream = Files.newBufferedWriter(path, StandardOpenOption.CREATE)) { + stream.write("bits,bool,bitset\n"); + + for (int i = 0; i <= 10_000_000; i += 500) { + System.out.println("Number of bits => " + i); + + boolean[] ba = new boolean[i]; + BitSet bitSet = new BitSet(i); + + long baSize = ClassLayout.parseInstance(ba).instanceSize(); + long bitSetSize = GraphLayout.parseInstance(bitSet).totalSize(); + + stream.write((i + "," + baSize + "," + bitSetSize + "\n")); + + if (i % 10_000 == 0) stream.flush(); + } + } + } +} diff --git a/jmh/src/main/java/com/baeldung/bitset/Sizing.java b/jmh/src/main/java/com/baeldung/bitset/Sizing.java new file mode 100644 index 0000000000..58c9061c07 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/bitset/Sizing.java @@ -0,0 +1,17 @@ +package com.baeldung.bitset; + +import org.openjdk.jol.info.ClassLayout; +import org.openjdk.jol.info.GraphLayout; + +import java.util.BitSet; + +public class Sizing { + + public static void main(String[] args) { + boolean[] ba = new boolean[10_000]; + System.out.println(ClassLayout.parseInstance(ba).toPrintable()); + + BitSet bitSet = new BitSet(10_000); + System.out.println(GraphLayout.parseInstance(bitSet).toPrintable()); + } +} diff --git a/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java b/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java new file mode 100644 index 0000000000..8949d4e117 --- /dev/null +++ b/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java @@ -0,0 +1,75 @@ +package com.baeldung.bitset; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; + +import java.util.BitSet; +import java.util.concurrent.ThreadLocalRandom; + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.Throughput) +public class VectorOfBitsBenchmark { + + private boolean[] array; + private BitSet bitSet; + + @Param({"100", "1000", "5000", "50000", "100000", "1000000", "2000000", "3000000", + "5000000", "7000000", "10000000", "20000000", "30000000", "50000000", "70000000", "1000000000"}) + public int size; + + @Setup(Level.Trial) + public void setUp() { + array = new boolean[size]; + for (int i = 0; i < array.length; i++) { + array[i] = ThreadLocalRandom.current().nextBoolean(); + } + + bitSet = new BitSet(size); + for (int i = 0; i < size; i++) { + bitSet.set(i, ThreadLocalRandom.current().nextBoolean()); + } + } + + @Benchmark + public boolean getBoolArray() { + return array[ThreadLocalRandom.current().nextInt(size)]; + } + + @Benchmark + public boolean getBitSet() { + return bitSet.get(ThreadLocalRandom.current().nextInt(size)); + } + + @Benchmark + public void setBoolArray() { + int index = ThreadLocalRandom.current().nextInt(size); + array[index] = true; + } + + @Benchmark + public void setBitSet() { + int index = ThreadLocalRandom.current().nextInt(size); + bitSet.set(index); + } + + @Benchmark + public int cardinalityBoolArray() { + int sum = 0; + for (boolean b : array) { + if (b) sum++; + } + + return sum; + } + + @Benchmark + public int cardinalityBitSet() { + return bitSet.cardinality(); + } +} diff --git a/jmh/src/main/resources/bitset/cardinal.csv b/jmh/src/main/resources/bitset/cardinal.csv new file mode 100644 index 0000000000..1e6f0731f4 --- /dev/null +++ b/jmh/src/main/resources/bitset/cardinal.csv @@ -0,0 +1,449 @@ +"Benchmark","Mode","Threads","Samples","Score","Score Error (99.9%)","Unit","Param: size" +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,393747573.686833,8176258.509541,"ops/s",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,0.001142,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,16.019285,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,3.525011,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,0.001011,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,0.000227,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,9.978252,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.000084,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,16.085984,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.000016,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,3.515332,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.000104,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.000187,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,51.807801,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,200028477.639536,1655942.004821,"ops/s",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,0.002157,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,30.037472,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,4.035148,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,0.002133,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,0.000533,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,14.964408,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.000209,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,30.189211,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.000035,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,4.026334,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.000222,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.000400,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,99.619362,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,63020698.220022,301117.329336,"ops/s",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,0.006739,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,92.968547,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,4.051628,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,0.005924,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,0.002165,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,29.892853,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.000582,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,93.493939,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.000109,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,4.051385,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.000724,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.001279,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,285.417873,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,7204008.548800,26777.006550,"ops/s",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,0.085737,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,796.749450,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,4.282982,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,0.055282,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,1.012529,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,110.884225,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.004487,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,801.165820,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.000784,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,4.226255,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.006024,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.010046,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,2006.941407,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,3629991.817907,11097.373770,"ops/s",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,0.243416,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,1577.873015,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,4.557042,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,0.106117,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,1.025199,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,205.866839,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.011796,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,1584.735453,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.002335,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,4.653284,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.012223,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.020736,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,3947.152509,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,363285.637971,1381.431204,"ops/s",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,1712.185003,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,15660.070795,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,9.441652,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,1.200677,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,1.744812,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,1963.525342,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.452116,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,15734.050011,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.023238,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,9.519313,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.190122,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.208191,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,38999.133661,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,180844.028528,610.040837,"ops/s",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,3664.111553,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,31271.600037,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,14.435729,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,2.610217,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,1.649819,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,3910.476252,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.217432,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,31408.622718,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.040256,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,14.601374,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.260903,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.422715,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,77788.657874,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,118548.730143,468.823226,"ops/s",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,5639.799222,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,47006.741115,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,19.832762,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,4.059959,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,2.278006,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,5874.367510,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.324499,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,47272.836745,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.064460,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,22.600079,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.467719,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.642886,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,116927.646081,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,70086.673236,563.669183,"ops/s",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,9560.498477,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,78198.576932,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,34.810483,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,6.905933,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,2.660745,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,9767.014432,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,0.616113,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,78630.286046,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.101142,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,31.958140,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,0.716475,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,0.975224,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,194453.814959,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,50185.268564,354.561055,"ops/s",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,13480.043453,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,109488.725728,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,45.881465,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,9.602892,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,2.750373,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,13686.896942,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,1.079668,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,110066.269505,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.186638,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,50.867881,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,1.087789,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,1.401113,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,272641.291312,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,34908.512595,116.418990,"ops/s",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,19358.228821,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,156380.208163,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,52.083219,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,13.328039,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,14.661694,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,19522.637780,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,2.203013,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,156928.984801,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,0.273531,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,67.026094,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,1.900268,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,1.929660,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,388765.349238,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,17317.558001,100.005388,"ops/s",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,38984.617172,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,312761.798113,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,110.924669,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,27.027104,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,11.114591,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,39043.188700,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,16.408157,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,314387.564881,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,1.315988,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,121.913794,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,7.243860,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,2.181325,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,778038.560011,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,11501.959917,57.124269,"ops/s",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,58960.217967,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,469304.081395,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,184.289676,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,48.075359,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,9.470284,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,58590.395636,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,110.391626,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,471624.463912,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,5.747181,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,162.875573,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,13.870816,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,1.683658,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,1168184.932237,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,6853.662641,34.907898,"ops/s",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,98396.707621,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,782412.601151,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,276.504336,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,62.269039,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,14.744583,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,97655.835705,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,463.063389,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,785788.480539,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,9.752381,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,309.916361,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,23.524244,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,3.349640,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,1946858.485637,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,4879.613096,31.364409,"ops/s",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,137967.751689,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,1096110.204019,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,460.349614,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,100.554744,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,21.779339,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,136829.273899,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,651.277926,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,1102431.584828,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,11.249848,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,520.978240,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,32.792037,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,3.967967,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,2727814.788476,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet","thrpt",4,40,224.865509,9.210752,"ops/s",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-load-misses","thrpt",4,2,1190415.055459,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-loads","thrpt",4,2,15632200.467402,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-dcache-stores","thrpt",4,2,19441.575768,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:L1-icache-load-misses","thrpt",4,2,2047.756107,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branch-misses","thrpt",4,2,485.442180,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:branches","thrpt",4,2,1965043.175621,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-load-misses","thrpt",4,2,31032.470870,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-loads","thrpt",4,2,15667116.799869,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-store-misses","thrpt",4,2,143.428283,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:dTLB-stores","thrpt",4,2,11595.673237,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-load-misses","thrpt",4,2,742.352246,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:iTLB-loads","thrpt",4,2,98.480752,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBitSet:instructions","thrpt",4,2,39048358.021105,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,37049279.373531,704963.020277,"ops/s",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,0.011099,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,112.064045,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,4.073352,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,0.009620,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,0.002608,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,29.947392,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,0.001015,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,112.623597,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,0.000228,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,4.075249,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,0.001286,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,0.002188,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,622.445960,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,4096591.017375,15272.062456,"ops/s",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,0.131963,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,1012.474032,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,4.586741,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,0.104217,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,1.022211,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,139.987103,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,0.008928,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,1017.535338,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,0.001594,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,4.600783,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,0.010615,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,0.018421,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,5536.843608,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,832334.798376,3074.911358,"ops/s",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,0.766809,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,5030.987321,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,7.002736,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,0.498173,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,1.086794,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,641.641634,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,0.047561,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,5051.582231,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,0.008993,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,6.752675,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,0.050431,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,0.092294,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,27529.642459,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,83377.631077,255.122714,"ops/s",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,539.461053,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,50020.851413,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,29.937221,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,5.092867,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,4.842983,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,6261.566122,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,0.422246,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,50255.455914,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,0.078430,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,24.798375,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,0.559565,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,0.902338,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,273680.241982,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,41408.544806,165.347056,"ops/s",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,1322.755020,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,99955.008469,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,55.552771,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,10.390631,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,5.861952,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,12500.640365,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,0.769535,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,100406.515812,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,0.150189,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,44.164416,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,1.117459,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,1.825801,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,546990.292774,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,4129.742795,17.898464,"ops/s",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,15349.951857,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,1002365.863265,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,499.940618,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,122.631357,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,28.242979,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,125323.009142,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,13.650726,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,1007023.362826,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,1.912985,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,505.608704,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,14.288697,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,17.956474,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,5484912.917616,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,2077.577519,7.337211,"ops/s",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,31292.588903,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,2001841.397596,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,966.586187,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,238.822058,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,46.510032,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,250019.595282,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,68.527514,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,2009528.999936,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,7.098600,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,950.622751,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,53.292000,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,24.529932,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,10953197.041140,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,1382.303027,4.169656,"ops/s",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,47056.390407,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,3000801.315529,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,1470.047881,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,357.378786,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,60.820713,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,374783.769835,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,252.896052,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,3015767.599869,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,21.872987,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,1524.876162,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,112.567929,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,23.688984,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,16425272.638241,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,829.757845,2.907395,"ops/s",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,79794.283301,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,4999110.374252,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,2878.569713,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,600.944033,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,117.854523,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,624380.185108,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,625.032361,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,5023239.665880,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,32.290537,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,1952.720560,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,194.797679,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,26.471072,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,27353169.238296,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,593.611980,2.520324,"ops/s",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,111485.949371,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,7025474.793043,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,3672.457662,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,817.906535,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,116.322549,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,877217.619856,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,957.823851,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,7057039.698064,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,50.812805,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,3850.388980,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,280.996635,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,55.292762,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,38432075.289421,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,414.148792,1.531335,"ops/s",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,158517.772914,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,10012879.292064,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,5067.772968,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,1159.247229,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,219.525384,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,1250534.640040,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,1355.116322,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,10051566.656711,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,68.965296,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,5208.287470,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,369.777199,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,56.291391,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,54776223.581884,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,207.806128,0.628873,"ops/s",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,304113.485355,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,20023501.895517,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,9779.441786,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,2487.972260,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,400.329711,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,2501297.068694,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,2937.078221,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,20089328.718289,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,131.879427,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,10912.262719,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,707.654814,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,108.177862,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,109579830.457931,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,138.119711,0.500755,"ops/s",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,443956.723054,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,30008750.271844,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,14759.175750,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,3431.902326,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,569.840892,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,3747872.534933,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,4806.051229,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,30144733.769549,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,201.619836,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,17338.732113,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,1098.261594,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,195.410627,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,164166517.089861,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,82.709149,0.295436,"ops/s",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,747996.211010,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,50109102.392841,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,37525.937305,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,6197.904618,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,1079.041011,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,6265857.125983,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,7401.558857,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,50190387.111098,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,343.424195,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,30593.259958,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,1746.881433,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,263.036555,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,274256325.159847,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,59.202337,0.381593,"ops/s",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,1049088.662627,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,70094037.559522,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,70850.762444,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,8257.515781,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,1934.286962,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,8780399.271839,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,10142.237142,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,70255089.174523,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,568.459880,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,60618.442280,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,2578.542787,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,369.873390,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,383542921.407972,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray","thrpt",4,40,4.164406,0.021372,"ops/s",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-load-misses","thrpt",4,2,14724055.231818,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-loads","thrpt",4,2,1002251097.850000,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-dcache-stores","thrpt",4,2,1304484.515909,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:L1-icache-load-misses","thrpt",4,2,94383.129545,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branch-misses","thrpt",4,2,29678.675000,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:branches","thrpt",4,2,126027016.040909,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-load-misses","thrpt",4,2,149098.588636,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-loads","thrpt",4,2,1005716183.827273,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-store-misses","thrpt",4,2,9554.579545,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:dTLB-stores","thrpt",4,2,1637043.229545,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-load-misses","thrpt",4,2,36110.963636,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:iTLB-loads","thrpt",4,2,5566.793182,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.cardinalityBoolArray:instructions","thrpt",4,2,5481003131.631819,NaN,"#/op",1000000000 diff --git a/jmh/src/main/resources/bitset/get.csv b/jmh/src/main/resources/bitset/get.csv new file mode 100644 index 0000000000..2d929d927d --- /dev/null +++ b/jmh/src/main/resources/bitset/get.csv @@ -0,0 +1,449 @@ +"Benchmark","Mode","Threads","Samples","Score","Score Error (99.9%)","Unit","Param: size" +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,184790139.562014,2667066.521846,"ops/s",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.002467,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.050243,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.042285,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002206,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.000451,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.985709,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000194,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.132320,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000034,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.035930,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000246,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000417,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.781944,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,189890949.805559,659556.001166,"ops/s",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.002317,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.036584,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.044334,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002032,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.000437,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.964305,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000185,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.148063,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000034,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.029343,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000246,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000403,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.597453,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,189507179.833915,629754.953530,"ops/s",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.002466,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.010134,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.029958,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002275,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.000384,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.962285,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000216,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.086110,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000033,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.018705,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000208,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000400,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.611799,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,185398269.303855,1908706.853646,"ops/s",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.003713,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.039282,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.044589,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002108,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.000501,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.976543,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000183,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.144876,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000032,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.036796,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000226,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000391,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.713651,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,187470455.311201,2138324.325624,"ops/s",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.005740,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.045473,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.049532,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002233,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.000559,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.975216,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000182,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.153817,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000042,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.032749,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000279,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000413,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.694265,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,187899335.193431,1227338.646447,"ops/s",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.757697,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.019129,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.035645,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002595,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.000815,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.962763,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000243,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.079796,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000043,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.018714,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000220,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000400,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.618577,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,181042070.478268,1034313.105183,"ops/s",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.882631,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.055692,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.046466,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.002913,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.001525,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.993797,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000303,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.145567,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000040,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.036471,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000231,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000414,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.837563,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,157845998.770241,1327029.686173,"ops/s",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.923265,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.039213,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.037515,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.003060,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.002237,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.989144,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000377,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.101674,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000044,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.029822,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000275,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000463,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.821119,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,140194241.226829,586052.963759,"ops/s",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.958165,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.065759,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.052019,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.003590,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.002185,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.995694,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000446,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.147433,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000054,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.039960,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000352,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000494,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.850007,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,134363547.905898,817872.600380,"ops/s",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.973091,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.083157,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.060888,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.003270,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.003700,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,13.012286,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.000645,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.162932,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000064,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.039776,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000402,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000526,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.956471,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,129938742.625757,565110.729002,"ops/s",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,0.982322,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.053334,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.051753,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.003960,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.004344,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,12.996532,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.001074,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.146765,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000087,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.040650,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000515,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000530,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.866671,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,125187585.586497,523512.098380,"ops/s",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,1.004652,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.080247,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.054714,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.003770,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.004486,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,13.010171,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.010580,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.154110,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000215,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.041480,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.000953,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000317,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.947671,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,115627724.299332,638665.572272,"ops/s",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,1.227419,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.079678,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.058129,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.004521,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.009050,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,13.012617,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,0.347392,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.142634,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000659,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.040588,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.001420,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000171,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,90.988720,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,103507035.990670,372081.425396,"ops/s",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,1.490488,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.059971,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.061928,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.004491,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.023517,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,13.022696,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,1.014237,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.140833,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000542,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.047774,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.001546,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000198,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,91.179548,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,100061443.949078,900762.613103,"ops/s",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,1.636879,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.089365,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.066827,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.004394,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.023939,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,13.054928,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,1.300501,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.169242,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.000755,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.059205,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.001714,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000271,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,91.429385,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet","thrpt",4,40,30732326.196764,1902855.641551,"ops/s",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-load-misses","thrpt",4,2,2.010809,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-loads","thrpt",4,2,19.363151,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-dcache-stores","thrpt",4,2,6.239644,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:L1-icache-load-misses","thrpt",4,2,0.014491,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branch-misses","thrpt",4,2,0.079687,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:branches","thrpt",4,2,13.302302,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-load-misses","thrpt",4,2,2.698668,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-loads","thrpt",4,2,19.522360,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-store-misses","thrpt",4,2,0.001826,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:dTLB-stores","thrpt",4,2,6.235821,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-load-misses","thrpt",4,2,0.004974,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:iTLB-loads","thrpt",4,2,0.000684,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBitSet:instructions","thrpt",4,2,93.483709,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,227276865.931318,1065421.113528,"ops/s",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.001953,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.036393,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.041004,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.001677,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.000390,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.983478,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.000158,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.114167,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000029,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.030073,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000194,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000334,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.747475,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,227967057.968084,1094391.643063,"ops/s",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.002196,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.038155,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.046080,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.001821,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.000377,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.983017,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.000151,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.121232,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000027,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.026809,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000171,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000319,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.269538,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,227488094.016039,1165579.055001,"ops/s",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.002484,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.046268,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.048022,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.001649,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.000417,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.993480,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.000191,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.116395,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000037,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.030824,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000201,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000356,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.847281,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,220590635.826749,3222316.343407,"ops/s",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.386152,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.014363,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.030620,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.001837,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.000445,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.970352,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.000175,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.071899,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000033,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.015771,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000197,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000347,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.159399,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,221812217.619440,1882356.038621,"ops/s",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.694581,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.036224,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.045287,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.002024,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.000413,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.985217,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.000159,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.113544,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000035,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.028587,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000209,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000352,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.781018,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,155300972.624227,1052925.157790,"ops/s",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.974041,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.024109,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.040972,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.002724,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.000890,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.983857,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.000635,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.114472,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000067,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.029008,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000370,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000485,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.276632,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,150139628.673692,671406.901317,"ops/s",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,0.991759,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.029834,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.039387,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.002965,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.001613,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.986406,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.002364,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.083273,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000157,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.020146,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.000647,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000345,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.274963,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,146544479.291686,722153.242446,"ops/s",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,1.019540,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.022684,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.043253,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.003449,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.002115,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,10.981744,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.025108,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.105318,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000364,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.024680,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.001022,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000151,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.769956,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,131610185.610556,544416.522700,"ops/s",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,1.450890,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.061835,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.056745,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.003605,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.002344,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.003703,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,0.764601,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.121742,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000585,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.033532,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.001213,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000137,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.911556,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,125543684.587399,707062.210707,"ops/s",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,1.681832,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.067818,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.051900,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.003963,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.003560,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.013663,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,1.126490,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.114877,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000538,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.039862,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.001300,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000148,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.996294,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,120883159.006800,459519.176985,"ops/s",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,1.941920,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.066701,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.057961,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.004200,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.004289,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.012477,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,1.402314,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.140748,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000749,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.049852,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.001377,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000179,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,74.017988,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,108406186.294073,582406.851629,"ops/s",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,2.395980,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.064172,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.058329,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.004261,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.004518,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.010508,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,1.726519,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.136526,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.000984,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.045655,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.001481,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000179,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.482638,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,87529931.443741,1955927.694142,"ops/s",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,2.594962,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.073273,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.063886,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.005067,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.009322,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.027283,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,1.845592,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.149139,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.001220,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.059616,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.001915,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000267,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,74.146192,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,52236198.372609,491642.796386,"ops/s",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,2.846910,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.152230,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.113607,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.009109,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.024525,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.088285,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,2.268730,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.251743,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.001259,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.092143,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.003064,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000363,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,73.596518,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,44791183.851884,214906.900295,"ops/s",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,2.967552,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.120575,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.109277,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.009707,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.024510,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.064747,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,2.499734,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.227798,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.001357,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.088992,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.003500,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000441,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,74.451386,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray","thrpt",4,40,37389103.890299,90477.383580,"ops/s",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-load-misses","thrpt",4,2,2.804161,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-loads","thrpt",4,2,18.310702,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-dcache-stores","thrpt",4,2,7.181002,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:L1-icache-load-misses","thrpt",4,2,0.011265,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branch-misses","thrpt",4,2,0.078800,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:branches","thrpt",4,2,11.274916,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-load-misses","thrpt",4,2,3.060411,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-loads","thrpt",4,2,18.390751,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-store-misses","thrpt",4,2,0.001505,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:dTLB-stores","thrpt",4,2,7.194463,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-load-misses","thrpt",4,2,0.004221,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:iTLB-loads","thrpt",4,2,0.000530,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.getBoolArray:instructions","thrpt",4,2,75.278465,NaN,"#/op",1000000000 diff --git a/jmh/src/main/resources/bitset/set.csv b/jmh/src/main/resources/bitset/set.csv new file mode 100644 index 0000000000..18b73bf989 --- /dev/null +++ b/jmh/src/main/resources/bitset/set.csv @@ -0,0 +1,449 @@ +"Benchmark","Mode","Threads","Samples","Score","Score Error (99.9%)","Unit","Param: size" +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,51896464.026542,75862.136758,"ops/s",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,0.455765,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.076844,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.058151,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.007209,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.001604,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,9.997170,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000671,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.155867,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000133,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.044563,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000883,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.001497,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,63.823169,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,70106741.257282,5675561.652157,"ops/s",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,0.701408,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,13.051907,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.038773,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.005106,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.001640,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,9.981827,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000487,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,13.108384,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000085,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.035609,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000635,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.001048,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.690961,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,95463073.139209,1113608.612106,"ops/s",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.081256,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,13.019534,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.030687,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003994,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.000999,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.961847,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000316,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,13.096411,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000053,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.025559,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000408,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000741,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,67.633459,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,118050031.787664,869821.142403,"ops/s",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.354826,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,11.035931,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.028466,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003085,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.000714,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.968244,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000300,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,11.094508,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000058,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.027209,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000403,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000643,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.685716,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,126298073.981831,369299.481879,"ops/s",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.310261,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,13.051825,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.033383,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003348,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.000801,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,9.997344,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000286,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,13.113142,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000045,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.022306,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000356,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000579,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,65.864528,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,130991668.121281,644042.215866,"ops/s",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.331196,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.047450,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.028621,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003152,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.001000,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.485817,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000319,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.101103,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000064,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.024312,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000369,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000587,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.301371,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,128165315.820896,496869.372046,"ops/s",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.377167,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,13.042081,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.031912,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003844,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.001726,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,9.984710,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000382,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,13.099182,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000066,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.020885,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000347,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000563,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,65.795765,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,125195342.161850,1957938.686648,"ops/s",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.384964,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.054831,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.031343,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003650,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.002185,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.499255,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000428,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.112498,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000084,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.027300,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000379,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000600,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.403520,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,133354250.565847,1255106.085613,"ops/s",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.320524,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.048234,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.028165,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003275,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.002304,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.488182,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000489,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.094041,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000097,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.023713,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000585,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000521,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.335488,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,137232624.452804,636350.199734,"ops/s",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.246943,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,13.025392,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.028421,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003476,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.003316,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,9.976549,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000551,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,13.085655,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000081,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.022321,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000476,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000522,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,65.766839,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,143989207.138248,756270.794340,"ops/s",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.182833,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.044035,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.027349,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003071,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.004236,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.491392,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.000717,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.088728,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.000137,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.026174,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000380,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000468,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.391401,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,151241501.714891,916836.288585,"ops/s",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.107189,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.041025,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.031621,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.002955,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.004243,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.497239,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.009641,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.098803,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.001624,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.024783,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.000804,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000269,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.415849,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,144263237.497241,732977.702789,"ops/s",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.295403,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.050585,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.033163,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003160,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.008815,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.508266,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.278706,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.108627,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.071757,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.030249,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.001102,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000163,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,66.538307,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,135443772.106893,604312.063062,"ops/s",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.597651,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,12.088824,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.049898,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003236,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.023795,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.565162,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,0.822377,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,12.127978,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.217013,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.047233,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.001227,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000186,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,67.051735,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,131423130.250911,685419.143744,"ops/s",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,1.830028,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,11.075647,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.048544,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.003294,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.023619,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,11.044497,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,1.021551,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,11.121959,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.318409,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.047471,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.001220,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000154,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,67.422027,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet","thrpt",4,40,50126275.321495,128366.907520,"ops/s",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-load-misses","thrpt",4,2,2.007914,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-loads","thrpt",4,2,13.283731,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-dcache-stores","thrpt",4,2,2.158816,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:L1-icache-load-misses","thrpt",4,2,0.009154,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branch-misses","thrpt",4,2,0.077561,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:branches","thrpt",4,2,10.255507,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-load-misses","thrpt",4,2,2.580432,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-loads","thrpt",4,2,13.332989,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-store-misses","thrpt",4,2,0.240555,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:dTLB-stores","thrpt",4,2,2.141680,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-load-misses","thrpt",4,2,0.003075,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:iTLB-loads","thrpt",4,2,0.000400,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBitSet:instructions","thrpt",4,2,68.183448,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,103190024.246958,1465075.410304,"ops/s",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.387288,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.061946,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.041483,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003577,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.001007,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.999897,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000288,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.121073,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.000058,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.034064,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000424,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000703,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.880071,NaN,"#/op",100 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,139443098.218536,1499104.709607,"ops/s",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.646658,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.016290,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.026692,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.002577,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.000566,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.966181,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000281,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.090556,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.000053,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.025779,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000324,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000544,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.677854,NaN,"#/op",1000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,141884743.566510,786570.828615,"ops/s",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.721487,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.046555,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.030607,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.002780,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.000635,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.999213,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000238,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.100109,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.000048,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.027592,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000322,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000530,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.883150,NaN,"#/op",5000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,141434121.940795,678907.202147,"ops/s",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.737588,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.009752,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.025647,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.002709,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.000564,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.966167,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000248,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.084263,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.000061,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.022513,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000310,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000559,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.676130,NaN,"#/op",50000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,141443758.907874,627442.604356,"ops/s",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.778842,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.031381,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.028014,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003220,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.000652,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.979226,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000287,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.089836,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.000071,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.023236,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000286,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000507,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.734083,NaN,"#/op",100000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,147240354.620049,715098.421473,"ops/s",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.974563,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.031177,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.024039,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003099,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.000948,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.989072,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000372,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.069719,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.000330,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.020618,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000355,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000477,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.839884,NaN,"#/op",1000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,153622403.885271,1327782.331450,"ops/s",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,0.991925,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.032598,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.024720,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003245,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.001456,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.991914,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.000825,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.079811,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.001852,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.024947,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000643,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000377,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.870424,NaN,"#/op",2000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,156527596.524201,795077.911203,"ops/s",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,1.014728,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.027806,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.024255,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003058,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.001984,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.990123,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.002815,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.076875,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.018651,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.022515,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.000962,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000127,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.871439,NaN,"#/op",3000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,158079426.644001,913191.923219,"ops/s",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,1.472277,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.052808,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.029994,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003121,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.002145,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.011432,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.004486,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.093163,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,0.766815,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.025713,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.001161,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000105,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,53.016947,NaN,"#/op",5000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,157390156.667728,672584.777681,"ops/s",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,1.695306,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.053664,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.031368,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003326,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.003155,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.010168,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.005645,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.095965,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,1.128123,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.028504,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.001011,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000110,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,53.003675,NaN,"#/op",7000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,157798980.940213,764697.250786,"ops/s",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,1.952853,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.022777,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.023807,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003257,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.004008,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,7.990682,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.004266,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.059754,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,1.397186,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.019997,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.001003,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000129,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.896245,NaN,"#/op",10000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,150330975.246741,1605620.715961,"ops/s",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,2.378773,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.036047,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.030046,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003117,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.004204,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.001242,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.005145,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.078731,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,1.708955,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.023010,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.001044,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000128,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,52.933174,NaN,"#/op",20000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,114316055.929498,3553753.935720,"ops/s",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,2.573253,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.049313,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.038018,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.003989,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.008927,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.014444,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.008533,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.094540,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,1.824349,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.033037,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.001348,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000178,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,53.081475,NaN,"#/op",30000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,62800524.051547,1844174.328399,"ops/s",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,2.806845,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.118333,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.069840,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.007308,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.024665,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.083796,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.010630,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.175443,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,2.245008,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.067306,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.002569,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000342,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,53.626962,NaN,"#/op",50000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,51085547.708493,526048.863875,"ops/s",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,2.914760,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.140406,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.094680,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.010137,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.024495,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.083728,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.010755,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.191453,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,2.472813,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.075312,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.002962,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000380,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,53.631291,NaN,"#/op",70000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray","thrpt",4,40,35331072.282690,115127.559672,"ops/s",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-load-misses","thrpt",4,2,2.877579,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-loads","thrpt",4,2,10.331614,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-dcache-stores","thrpt",4,2,2.181433,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:L1-icache-load-misses","thrpt",4,2,0.013025,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branch-misses","thrpt",4,2,0.078282,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:branches","thrpt",4,2,8.293426,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-load-misses","thrpt",4,2,0.014965,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-loads","thrpt",4,2,10.351742,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-store-misses","thrpt",4,2,3.067687,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:dTLB-stores","thrpt",4,2,2.142323,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-load-misses","thrpt",4,2,0.004301,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:iTLB-loads","thrpt",4,2,0.000614,NaN,"#/op",1000000000 +"com.baeldung.bitset.VectorOfBitsBenchmark.setBoolArray:instructions","thrpt",4,2,55.399010,NaN,"#/op",1000000000 From ed51104e26ff61c9c245ccfbe53998cb41a2c768 Mon Sep 17 00:00:00 2001 From: vatsalgosar Date: Fri, 31 Jul 2020 01:26:27 +0530 Subject: [PATCH 114/155] BAEL-3941 (#9499) * BAEL-3941 - Code snippets for preserving line breaks using Jsoup while parsing HTML strings * BAEL-3941 - swapped the order of arguments in assertEquals --- .../jsoup/PreservingLineBreaksUnitTest.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java diff --git a/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java new file mode 100644 index 0000000000..0958fa96e2 --- /dev/null +++ b/jsoup/src/test/java/com/baeldung/jsoup/PreservingLineBreaksUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.jsoup; + +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +import org.jsoup.safety.Whitelist; +import org.junit.Test; +import static org.junit.Assert.assertEquals; + +public class PreservingLineBreaksUnitTest { + + @Test + public void whenBackSlashNNewLineCharacter_thenPreserveLineBreak() { + String strHTML = "Hello\nworld"; + Document.OutputSettings outputSettings = new Document.OutputSettings(); + outputSettings.prettyPrint(false); + String strWithNewLines = Jsoup.clean(strHTML, "", Whitelist.none(), outputSettings); + assertEquals("Hello\nworld", strWithNewLines); + } + + @Test + public void whenHTMLNewLineCharacters_thenPreserveLineBreak() { + String strHTML = "" + + "Hello" + + "
" + + "World" + + "

Paragraph

" + + ""; + Document jsoupDoc = Jsoup.parse(strHTML); + Document.OutputSettings outputSettings = new Document.OutputSettings(); + outputSettings.prettyPrint(false); + jsoupDoc.outputSettings(outputSettings); + jsoupDoc.select("br").before("\\n"); + jsoupDoc.select("p").before("\\n"); + String str = jsoupDoc.html().replaceAll("\\\\n", "\n"); + String strWithNewLines = + Jsoup.clean(str, "", Whitelist.none(), outputSettings); + assertEquals("Hello\nWorld\nParagraph", strWithNewLines); + } +} From 749bd7e99a5e25124434b8cba97d8bcc2f425459 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 31 Jul 2020 15:26:27 +0430 Subject: [PATCH 115/155] Improve the Kotlin Jackson module --- .../kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt index 84171d9019..95df57fb1e 100644 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt @@ -59,7 +59,11 @@ class JacksonUnitTest { val aMap: Map = mapper.readValue(json) assertEquals(aMap[1], "one") - assertEquals(aMap[2], "two") + assertEquals(aMap[2], "two") + + val sameMap = mapper.readValue>(json) + assertEquals(sameMap[1], "one") + assertEquals(sameMap[2], "two") } @Test From 508b4a2939cb8170a75c51ac20a3b3c65c6519f9 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 31 Jul 2020 15:31:51 +0430 Subject: [PATCH 116/155] Added Reified Style to the List Example --- .../kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt index 95df57fb1e..0c72edc2fd 100644 --- a/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt +++ b/kotlin-libraries-2/src/test/kotlin/com/baeldung/kotlin/jackson/JacksonUnitTest.kt @@ -85,7 +85,11 @@ class JacksonUnitTest { val movie1 = Movie("Endgame", "Marvel", 9.2f) val movie2 = Movie("Shazam", "Warner Bros", 7.6f) assertTrue(movieList.contains(movie1)) - assertTrue(movieList.contains(movie2)) + assertTrue(movieList.contains(movie2)) + + val sameList = mapper.readValue>(json) + assertTrue(sameList.contains(movie1)) + assertTrue(sameList.contains(movie2)) } @Test From c748e8172352f8e65401048c6d668e1cdac4f102 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Fri, 31 Jul 2020 22:02:44 +0200 Subject: [PATCH 117/155] JAVA-17: Move Running Setup Data on Startup in Spring into spring-boot-data --- spring-boot-modules/spring-boot-data/README.md | 1 + .../com/baeldung/startup/AllStrategiesExampleBean.java | 1 - .../com/baeldung/startup/EventListenerExampleBean.java | 1 - .../java/com/baeldung/startup/InitMethodExampleBean.java | 4 ++-- .../com/baeldung/startup/InitializingBeanExampleBean.java | 4 ++-- .../java/com/baeldung/startup/InvalidInitExampleBean.java | 0 .../baeldung/startup/LogicInConstructorExampleBean.java | 4 ++-- .../com/baeldung/startup/PostConstructExampleBean.java | 7 +++---- .../java/com/baeldung/startup/SpringStartupConfig.java | 0 .../startup/StartupApplicationListenerExample.java | 1 - .../spring-boot-data}/src/main/resources/startupConfig.xml | 0 .../com/baeldung/startup/SpringStartupIntegrationTest.java | 0 .../startup/SpringStartupXMLConfigIntegrationTest.java | 0 spring-boot-modules/spring-boot/README.MD | 1 - spring-core-4/README.md | 1 - 15 files changed, 10 insertions(+), 15 deletions(-) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java (99%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/EventListenerExampleBean.java (99%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/InitMethodExampleBean.java (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/PostConstructExampleBean.java (99%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/SpringStartupConfig.java (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java (99%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/main/resources/startupConfig.xml (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java (100%) rename {spring-core-4 => spring-boot-modules/spring-boot-data}/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java (100%) diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index faa38d475e..98589cf2d2 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -10,3 +10,4 @@ This module contains articles about Spring Boot with Spring Data - [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) - [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) +- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) diff --git a/spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java similarity index 99% rename from spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java index e08309d474..53b81da340 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/AllStrategiesExampleBean.java @@ -2,7 +2,6 @@ package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.springframework.beans.factory.InitializingBean; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; diff --git a/spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/EventListenerExampleBean.java similarity index 99% rename from spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/EventListenerExampleBean.java index a76fc6a2b2..8a2e36ed8e 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/EventListenerExampleBean.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/EventListenerExampleBean.java @@ -2,7 +2,6 @@ package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; diff --git a/spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InitMethodExampleBean.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InitMethodExampleBean.java index a3b12028d1..86f61dd395 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/InitMethodExampleBean.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InitMethodExampleBean.java @@ -1,7 +1,5 @@ package com.baeldung.startup; -import java.util.Arrays; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -9,6 +7,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import java.util.Arrays; + @Component @Scope(value = "prototype") public class InitMethodExampleBean { diff --git a/spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java index c625a172fd..8fef3bf8b7 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InitializingBeanExampleBean.java @@ -1,7 +1,5 @@ package com.baeldung.startup; -import java.util.Arrays; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; @@ -10,6 +8,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import java.util.Arrays; + @Component @Scope(value = "prototype") public class InitializingBeanExampleBean implements InitializingBean { diff --git a/spring-core-4/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/InvalidInitExampleBean.java diff --git a/spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java index ade7573bbe..b4a102b09d 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/LogicInConstructorExampleBean.java @@ -1,7 +1,5 @@ package com.baeldung.startup; -import java.util.Arrays; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -9,6 +7,8 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import java.util.Arrays; + @Component @Scope(value = "prototype") public class LogicInConstructorExampleBean { diff --git a/spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/PostConstructExampleBean.java similarity index 99% rename from spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/PostConstructExampleBean.java index 1001043d86..337aa1520a 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/PostConstructExampleBean.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/PostConstructExampleBean.java @@ -1,9 +1,5 @@ package com.baeldung.startup; -import java.util.Arrays; - -import javax.annotation.PostConstruct; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -11,6 +7,9 @@ import org.springframework.context.annotation.Scope; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import javax.annotation.PostConstruct; +import java.util.Arrays; + @Component @Scope(value = "prototype") public class PostConstructExampleBean { diff --git a/spring-core-4/src/main/java/com/baeldung/startup/SpringStartupConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/SpringStartupConfig.java similarity index 100% rename from spring-core-4/src/main/java/com/baeldung/startup/SpringStartupConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/SpringStartupConfig.java diff --git a/spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java similarity index 99% rename from spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java index 2cc5e6abcb..345fb3a625 100644 --- a/spring-core-4/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/startup/StartupApplicationListenerExample.java @@ -2,7 +2,6 @@ package com.baeldung.startup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; diff --git a/spring-core-4/src/main/resources/startupConfig.xml b/spring-boot-modules/spring-boot-data/src/main/resources/startupConfig.xml similarity index 100% rename from spring-core-4/src/main/resources/startupConfig.xml rename to spring-boot-modules/spring-boot-data/src/main/resources/startupConfig.xml diff --git a/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupIntegrationTest.java diff --git a/spring-core-4/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java similarity index 100% rename from spring-core-4/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/startup/SpringStartupXMLConfigIntegrationTest.java diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.MD index fb1c20e988..c95fe51842 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.MD @@ -25,4 +25,3 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) - [Validation in Spring Boot](https://www.baeldung.com/spring-boot-bean-validation) -- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) diff --git a/spring-core-4/README.md b/spring-core-4/README.md index 83b5c4933d..03a6747c1d 100644 --- a/spring-core-4/README.md +++ b/spring-core-4/README.md @@ -9,7 +9,6 @@ This module contains articles about core Spring functionality - [Spring @Import Annotation](https://www.baeldung.com/spring-import-annotation) - [Spring BeanPostProcessor](https://www.baeldung.com/spring-beanpostprocessor) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) - [The Spring ApplicationContext](https://www.baeldung.com/spring-application-context) - More articles: [[<-- prev]](/spring-core-3) From 21342c2f46c08e54b8bc3cf259f78e99b34e1f4a Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Sat, 1 Aug 2020 20:40:45 +0430 Subject: [PATCH 118/155] Resolved the Comments --- jmh/src/main/java/com/baeldung/bitset/Plotter.java | 4 +++- .../java/com/baeldung/bitset/VectorOfBitsBenchmark.java | 8 +++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/jmh/src/main/java/com/baeldung/bitset/Plotter.java b/jmh/src/main/java/com/baeldung/bitset/Plotter.java index beb136f515..0d065ea185 100644 --- a/jmh/src/main/java/com/baeldung/bitset/Plotter.java +++ b/jmh/src/main/java/com/baeldung/bitset/Plotter.java @@ -29,7 +29,9 @@ public class Plotter { stream.write((i + "," + baSize + "," + bitSetSize + "\n")); - if (i % 10_000 == 0) stream.flush(); + if (i % 10_000 == 0) { + stream.flush(); + } } } } diff --git a/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java b/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java index 8949d4e117..7bbf00f36c 100644 --- a/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java +++ b/jmh/src/main/java/com/baeldung/bitset/VectorOfBitsBenchmark.java @@ -19,8 +19,8 @@ public class VectorOfBitsBenchmark { private boolean[] array; private BitSet bitSet; - @Param({"100", "1000", "5000", "50000", "100000", "1000000", "2000000", "3000000", - "5000000", "7000000", "10000000", "20000000", "30000000", "50000000", "70000000", "1000000000"}) + @Param({"100", "1000", "5000", "50000", "100000", "1000000", "2000000", "3000000", "5000000", + "7000000", "10000000", "20000000", "30000000", "50000000", "70000000", "1000000000"}) public int size; @Setup(Level.Trial) @@ -62,7 +62,9 @@ public class VectorOfBitsBenchmark { public int cardinalityBoolArray() { int sum = 0; for (boolean b : array) { - if (b) sum++; + if (b) { + sum++; + } } return sum; From 623eaff91dae4c40d79588d350d0869f8bf53208 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 2 Aug 2020 00:55:58 +0530 Subject: [PATCH 119/155] ingore files generated after build --- .gitignore | 1 + spring-soap/.gitignore | 1 + spring-soap/pom.xml | 1 + .../java/com/baeldung/springsoap/client/gen/Country.java | 7 ------- .../java/com/baeldung/springsoap/client/gen/Currency.java | 7 ------- .../baeldung/springsoap/client/gen/GetCountryRequest.java | 7 ------- .../baeldung/springsoap/client/gen/GetCountryResponse.java | 7 ------- .../com/baeldung/springsoap/client/gen/ObjectFactory.java | 7 ------- .../com/baeldung/springsoap/client/gen/package-info.java | 7 ------- 9 files changed, 3 insertions(+), 42 deletions(-) diff --git a/.gitignore b/.gitignore index c54117203f..fe56746dfd 100644 --- a/.gitignore +++ b/.gitignore @@ -85,5 +85,6 @@ transaction.log *-shell.log apache-cxf/cxf-aegis/baeldung.xml +testing-modules/report-*.json libraries-2/*.db \ No newline at end of file diff --git a/spring-soap/.gitignore b/spring-soap/.gitignore index b83d22266a..cce17abdb9 100644 --- a/spring-soap/.gitignore +++ b/spring-soap/.gitignore @@ -1 +1,2 @@ /target/ +sun-jaxb.episode diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 137ff03c31..bea3d033e6 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -75,6 +75,7 @@ ${project.basedir}/src/main/java com.baeldung.springsoap.client.gen ${project.basedir}/src/main/resources + true countries.wsdl diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java index e17dce55f9..bb196d625d 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Country.java @@ -1,10 +1,3 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 -// See https://javaee.github.io/jaxb-v2/ -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2020.04.25 at 03:18:49 PM IST -// - package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java index 12fdef58c2..023a8103e5 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/Currency.java @@ -1,10 +1,3 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 -// See https://javaee.github.io/jaxb-v2/ -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2020.04.25 at 03:18:49 PM IST -// - package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java index 5739ee3b96..dcd5b1f08b 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryRequest.java @@ -1,10 +1,3 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 -// See https://javaee.github.io/jaxb-v2/ -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2020.04.25 at 03:18:49 PM IST -// - package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java index ba1ab56cf8..11135c32e1 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/GetCountryResponse.java @@ -1,10 +1,3 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 -// See https://javaee.github.io/jaxb-v2/ -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2020.04.25 at 03:18:49 PM IST -// - package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java index 88b27245be..e6d56d5aba 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/ObjectFactory.java @@ -1,10 +1,3 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 -// See https://javaee.github.io/jaxb-v2/ -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2020.04.25 at 03:18:49 PM IST -// - package com.baeldung.springsoap.client.gen; diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java index eefed169a8..9432e0c328 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/client/gen/package-info.java @@ -1,9 +1,2 @@ -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0 -// See https://javaee.github.io/jaxb-v2/ -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2020.04.25 at 03:18:49 PM IST -// - @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/springsoap/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.baeldung.springsoap.client.gen; From f18d4dfa987399981d3c4e9dddaaf4cd5588d7f6 Mon Sep 17 00:00:00 2001 From: Sampada <46674082+sampada07@users.noreply.github.com> Date: Sun, 2 Aug 2020 01:39:35 +0530 Subject: [PATCH 120/155] BAEL-3836: Fix failing test in core-java-concurrency-advanced-3 (#9806) * BAEL-3836: Fix failing test in core-java-concurrency-advanced-3 * BAEL-3836: Fix failing test in core-java-concurrency-advanced-3 --- ...UnitManualTest.java => PrimeNumbersManualTest.java} | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) rename core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/{PrimeNumbersUnitManualTest.java => PrimeNumbersManualTest.java} (93%) diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitManualTest.java b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersManualTest.java similarity index 93% rename from core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitManualTest.java rename to core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersManualTest.java index 4fbbef4e61..8d12218c05 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersUnitManualTest.java +++ b/core-java-modules/core-java-concurrency-advanced-3/src/test/java/com/baeldung/workstealing/PrimeNumbersManualTest.java @@ -15,7 +15,15 @@ import java.util.logging.Logger; import static org.junit.Assert.fail; -public class PrimeNumbersUnitManualTest { +/** + * This test expects the file target/test-classes/META-INF/BenchmarkList to be present. + * + * Before running the test ensure that the file is present. + * If not, please run mvn install on the module. + * + */ + +public class PrimeNumbersManualTest { private static Logger logger = Logger.getAnonymousLogger(); From 71cd51e85fe028784c1a7c936289fa88f30214ff Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 2 Aug 2020 02:07:30 +0530 Subject: [PATCH 121/155] align module name & artifactId --- persistence-modules/flyway-repair/pom.xml | 2 +- persistence-modules/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/persistence-modules/flyway-repair/pom.xml b/persistence-modules/flyway-repair/pom.xml index 4d61bd5c0e..5a5c4103f6 100644 --- a/persistence-modules/flyway-repair/pom.xml +++ b/persistence-modules/flyway-repair/pom.xml @@ -2,7 +2,7 @@ 4.0.0 - flyway + flyway-repair flyway-repair jar Flyway Repair Demo diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index c598ad8805..31b9aaaf6d 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -19,7 +19,7 @@ core-java-persistence deltaspike elasticsearch - flyway + flyway-repair hbase hibernate5 hibernate-mapping From 6fc0c42586e2c85390a5d58cfbf43cc994482083 Mon Sep 17 00:00:00 2001 From: Maja Joksovic Date: Sat, 1 Aug 2020 22:58:00 +0200 Subject: [PATCH 122/155] fixed indentation --- .../com/baeldung/copydirectory/JavaNio.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java index fe1eb59c64..b574042ee5 100644 --- a/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java +++ b/core-java-modules/core-java-io-3/src/main/java/com/baeldung/copydirectory/JavaNio.java @@ -9,14 +9,14 @@ public class JavaNio { public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation) throws IOException { Files.walk(Paths.get(sourceDirectoryLocation)) - .forEach(source -> { - Path destination = Paths.get(destinationDirectoryLocation, source.toString() - .substring(sourceDirectoryLocation.length())); - try { - Files.copy(source, destination); - } catch (IOException e) { - e.printStackTrace(); - } - }); + .forEach(source -> { + Path destination = Paths.get(destinationDirectoryLocation, source.toString() + .substring(sourceDirectoryLocation.length())); + try { + Files.copy(source, destination); + } catch (IOException e) { + e.printStackTrace(); + } + }); } } From 314910468f9981eb884bb4279526eaccb68b146b Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 2 Aug 2020 03:47:35 +0530 Subject: [PATCH 123/155] used release repository --- maven-modules/versions-maven-plugin/original/pom.xml | 6 +++--- maven-modules/versions-maven-plugin/pom.xml | 6 +++--- parent-kotlin/pom.xml | 4 ++-- spring-boot-modules/spring-boot-mvc-2/pom.xml | 6 +++--- spring-boot-modules/spring-boot-mvc/pom.xml | 6 +++--- spring-mobile/pom.xml | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/maven-modules/versions-maven-plugin/original/pom.xml b/maven-modules/versions-maven-plugin/original/pom.xml index f81596661e..f705dae5c5 100644 --- a/maven-modules/versions-maven-plugin/original/pom.xml +++ b/maven-modules/versions-maven-plugin/original/pom.xml @@ -58,9 +58,9 @@ - apache.snapshots - Apache Development Snapshot Repository - https://repository.apache.org/content/repositories/snapshots/ + apache.releases + Apache Development Release Repository + https://repository.apache.org/content/repositories/releases/ false diff --git a/maven-modules/versions-maven-plugin/pom.xml b/maven-modules/versions-maven-plugin/pom.xml index 9793f55b28..3a9134ff40 100644 --- a/maven-modules/versions-maven-plugin/pom.xml +++ b/maven-modules/versions-maven-plugin/pom.xml @@ -57,9 +57,9 @@ - apache.snapshots - Apache Development Snapshot Repository - https://repository.apache.org/content/repositories/snapshots/ + apache.releases + Apache Development Release Repository + https://repository.apache.org/content/repositories/releases/ false diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index 947dd20483..f8a95e235a 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -30,8 +30,8 @@ spring-milestone - Spring Milestone Repository - https://repo.spring.io/milestone + Spring Release Repository + https://repo.spring.io/release diff --git a/spring-boot-modules/spring-boot-mvc-2/pom.xml b/spring-boot-modules/spring-boot-mvc-2/pom.xml index 73a75f020c..0b9213a7ea 100644 --- a/spring-boot-modules/spring-boot-mvc-2/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-2/pom.xml @@ -90,15 +90,15 @@ - jcenter-snapshots + jcenter-release jcenter - http://oss.jfrog.org/artifactory/oss-snapshot-local/ + http://oss.jfrog.org/artifactory/oss-release-local/ - 3.0.0-SNAPSHOT + 3.0.0 com.baeldung.swagger2boot.SpringBootSwaggerApplication 1.4.11.1 diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index fd6f1b0a8a..9ae6d8341a 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -20,9 +20,9 @@ - jcenter-snapshots + jcenter-release jcenter - http://oss.jfrog.org/artifactory/oss-snapshot-local/ + http://oss.jfrog.org/artifactory/oss-release-local/ @@ -148,7 +148,7 @@ - 3.0.0-SNAPSHOT + 3.0.0 1.10.0 2.3.7 diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 465458ba49..bb2b418a55 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -33,8 +33,8 @@ spring-milestones - Spring Milestones - https://repo.spring.io/libs-milestone + Spring Release + https://repo.spring.io/libs-release false From bff407ca059e733f1aea457e78a5c477a3654255 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 2 Aug 2020 03:51:32 +0530 Subject: [PATCH 124/155] used release repository --- parent-kotlin/pom.xml | 4 ++-- spring-mobile/pom.xml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/parent-kotlin/pom.xml b/parent-kotlin/pom.xml index f8a95e235a..947dd20483 100644 --- a/parent-kotlin/pom.xml +++ b/parent-kotlin/pom.xml @@ -30,8 +30,8 @@ spring-milestone - Spring Release Repository - https://repo.spring.io/release + Spring Milestone Repository + https://repo.spring.io/milestone diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index bb2b418a55..465458ba49 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -33,8 +33,8 @@ spring-milestones - Spring Release - https://repo.spring.io/libs-release + Spring Milestones + https://repo.spring.io/libs-milestone false From 80091e154ad6b6d0293ccb7997e26af601dafc01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Sun, 2 Aug 2020 13:27:31 +0200 Subject: [PATCH 125/155] [JAVA-2276] Upgraded maven-assembly-plugin version to 3.3.0 (#9801) --- spring-boot-modules/spring-boot-crud/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-crud/pom.xml b/spring-boot-modules/spring-boot-crud/pom.xml index 8ba7bab171..a4be360b0f 100644 --- a/spring-boot-modules/spring-boot-crud/pom.xml +++ b/spring-boot-modules/spring-boot-crud/pom.xml @@ -63,6 +63,7 @@ org.apache.maven.plugins maven-assembly-plugin + 3.3.0 jar-with-dependencies From 8527d5806334d266ac13e91acd0f6cf34a02bae9 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Sun, 2 Aug 2020 20:00:53 +0430 Subject: [PATCH 126/155] BAEL-4391: Check if a file exists in Java (#9748) * Check if a file exists in Java * Simple Assertions --- core-java-modules/core-java-io-3/.gitignore | 2 + .../baeldung/existence/ExistenceUnitTest.java | 91 +++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 core-java-modules/core-java-io-3/.gitignore create mode 100644 core-java-modules/core-java-io-3/src/test/java/com/baeldung/existence/ExistenceUnitTest.java diff --git a/core-java-modules/core-java-io-3/.gitignore b/core-java-modules/core-java-io-3/.gitignore new file mode 100644 index 0000000000..0c0cd871c5 --- /dev/null +++ b/core-java-modules/core-java-io-3/.gitignore @@ -0,0 +1,2 @@ +test-link* +0.* \ No newline at end of file diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/existence/ExistenceUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/existence/ExistenceUnitTest.java new file mode 100644 index 0000000000..c52e46e8c1 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/existence/ExistenceUnitTest.java @@ -0,0 +1,91 @@ +package com.baeldung.existence; + +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.ThreadLocalRandom; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ExistenceUnitTest { + + @Test + public void givenFile_whenDoesNotExist_thenFilesReturnsFalse() { + Path path = Paths.get("does-not-exist.txt"); + + assertFalse(Files.exists(path)); + assertTrue(Files.notExists(path)); + } + + @Test + public void givenFile_whenExists_thenFilesShouldReturnTrue() throws IOException { + Path tempFile = Files.createTempFile("baeldung", "exist-nio"); + assertTrue(Files.exists(tempFile)); + assertFalse(Files.notExists(tempFile)); + + Path tempDirectory = Files.createTempDirectory("baeldung-exists"); + assertTrue(Files.exists(tempDirectory)); + assertFalse(Files.notExists(tempDirectory)); + + assertTrue(Files.isDirectory(tempDirectory)); + assertFalse(Files.isDirectory(tempFile)); + assertTrue(Files.isRegularFile(tempFile)); + + assertTrue(Files.isReadable(tempFile)); + + Files.deleteIfExists(tempFile); + Files.deleteIfExists(tempDirectory); + } + + @Test + public void givenSymbolicLink_whenTargetDoesNotExists_thenFollowOrNotBasedOnTheOptions() throws IOException { + Path target = Files.createTempFile("baeldung", "target"); + Path symbol = Paths.get("test-link-" + ThreadLocalRandom.current().nextInt()); + + Path symbolicLink = Files.createSymbolicLink(symbol, target); + assertTrue(Files.exists(symbolicLink)); + assertTrue(Files.isSymbolicLink(symbolicLink)); + assertFalse(Files.isSymbolicLink(target)); + + Files.deleteIfExists(target); + assertFalse(Files.exists(symbolicLink)); + assertTrue(Files.exists(symbolicLink, LinkOption.NOFOLLOW_LINKS)); + + Files.deleteIfExists(symbolicLink); + } + + @Test + public void givenFile_whenDoesNotExist_thenFileReturnsFalse() { + assertFalse(new File("invalid").exists()); + assertFalse(new File("invalid").isFile()); + } + + @Test + public void givenFile_whenExist_thenShouldReturnTrue() throws IOException { + Path tempFilePath = Files.createTempFile("baeldung", "exist-io"); + Path tempDirectoryPath = Files.createTempDirectory("baeldung-exists-io"); + + File tempFile = new File(tempFilePath.toString()); + File tempDirectory = new File(tempDirectoryPath.toString()); + + assertTrue(tempFile.exists()); + assertTrue(tempDirectory.exists()); + + assertTrue(tempFile.isFile()); + assertFalse(tempDirectory.isFile()); + + assertTrue(tempDirectory.isDirectory()); + assertFalse(tempFile.isDirectory()); + + assertTrue(tempFile.canRead()); + + Files.deleteIfExists(tempFilePath); + Files.deleteIfExists(tempDirectoryPath); + } +} From 353f454fe0488399998996ca82144509988a03f3 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Sun, 2 Aug 2020 20:06:13 +0430 Subject: [PATCH 127/155] Improve How to Count the Number of Matches for a Regex? (#9788) --- .../baeldung/regex/countmatches/CountMatchesUnitTest.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/countmatches/CountMatchesUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/countmatches/CountMatchesUnitTest.java index 6427d11dd6..3e601a7828 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/countmatches/CountMatchesUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/countmatches/CountMatchesUnitTest.java @@ -1,12 +1,11 @@ package com.baeldung.regex.countmatches; -import static org.junit.Assert.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.Test; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit Test intended to count number of matches of a RegEx using Java 8 and 9. @@ -65,7 +64,7 @@ public class CountMatchesUnitTest { count++; } - assertNotEquals(3, count); + assertEquals(2, count); } @Test From 7ec5e6824e7dfcaf3022fe4a0f4bc9d43a4a497e Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Sun, 2 Aug 2020 22:36:02 +0530 Subject: [PATCH 128/155] Refactored code to use short primitive instead of Short wrapper class. --- .../reflection/set/fields/Person.java | 87 ------------------- .../SetFieldsUsingReflectionUnitTest.java | 4 +- 2 files changed, 3 insertions(+), 88 deletions(-) delete mode 100644 core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java diff --git a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java b/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java deleted file mode 100644 index 6bdfc58d78..0000000000 --- a/core-java-modules/core-java-reflection-2/src/main/java/com/baeldung/reflection/set/fields/Person.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.baeldung.reflection.set.fields; - -public class Person { - - private String name; - private byte age; - private short uidNumber; - private int pinCode; - private long contactNumber; - private float height; - private double weight; - private char gender; - private boolean active; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public byte getAge() { - return age; - } - - public void setAge(byte age) { - this.age = age; - } - - public short getUidNumber() { - return uidNumber; - } - - public void setUidNumber(short uidNumber) { - this.uidNumber = uidNumber; - } - - public int getPinCode() { - return pinCode; - } - - public void setPinCode(int pinCode) { - this.pinCode = pinCode; - } - - public long getContactNumber() { - return contactNumber; - } - - public void setContactNumber(long contactNumber) { - this.contactNumber = contactNumber; - } - - public float getHeight() { - return height; - } - - public void setHeight(float height) { - this.height = height; - } - - public double getWeight() { - return weight; - } - - public void setWeight(double weight) { - this.weight = weight; - } - - public char getGender() { - return gender; - } - - public void setGender(char gender) { - this.gender = gender; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } - -} diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java index 18a378cf07..8931d22160 100644 --- a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java @@ -5,6 +5,8 @@ import java.lang.reflect.Field; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import com.baeldung.reflection.access.privatefields.Person; + public class SetFieldsUsingReflectionUnitTest { @Test @@ -66,7 +68,7 @@ public class SetFieldsUsingReflectionUnitTest { .getDeclaredField("pinCode"); pinCodeField.setAccessible(true); - Short pinCode = 4110; + short pinCode = 4110; pinCodeField.setInt(person, pinCode); Assertions.assertEquals(4110, person.getPinCode()); } From 254319fb306b3e4595751ca67d3bec1a2658c933 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Sun, 2 Aug 2020 23:17:57 +0530 Subject: [PATCH 129/155] JAVA-2297: Update "Spring Boot custom error page" article --- .../spring-boot-basic-customization/pom.xml | 10 ++++++---- .../errorhandling/controllers/MyErrorController.java | 2 +- .../src/main/resources/application.properties | 1 + 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/spring-boot-modules/spring-boot-basic-customization/pom.xml b/spring-boot-modules/spring-boot-basic-customization/pom.xml index fc34994a85..2a4b321c5f 100644 --- a/spring-boot-modules/spring-boot-basic-customization/pom.xml +++ b/spring-boot-modules/spring-boot-basic-customization/pom.xml @@ -4,11 +4,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT - ../ + org.springframework.boot + spring-boot-starter-parent + 2.3.2.RELEASE + spring-boot-basic-customization diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java index e002ac045d..8a7a3d6e45 100644 --- a/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/java/com/baeldung/errorhandling/controllers/MyErrorController.java @@ -34,7 +34,7 @@ public class MyErrorController implements ErrorController { @Override public String getErrorPath() { - return "/error"; + return null; } } diff --git a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties index 4d4a6ec7bd..53f13c4767 100644 --- a/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-basic-customization/src/main/resources/application.properties @@ -5,3 +5,4 @@ #spring.banner.image.height= //TODO #spring.banner.image.margin= //TODO #spring.banner.image.invert= //TODO +server.error.path=/error From 33841c2034a82feb31714f986d4cb3441f56ceda Mon Sep 17 00:00:00 2001 From: joe zhang Date: Mon, 3 Aug 2020 22:52:22 +0800 Subject: [PATCH 130/155] use utility class directly --- .../primitivetype/PrimitiveTypeUtil.java | 16 +------- .../primitivetype/PrimitiveTypeUnitTest.java | 40 ++++++++++++++++++ .../PrimitiveTypeUtilUnitTest.java | 41 ------------------- 3 files changed, 42 insertions(+), 55 deletions(-) create mode 100644 core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java delete mode 100644 core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java index 1b2083b548..9607a0008f 100644 --- a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java @@ -3,10 +3,6 @@ package com.baeldung.primitivetype; import java.util.HashMap; import java.util.Map; -import org.apache.commons.lang3.ClassUtils; - -import com.google.common.primitives.Primitives; - public class PrimitiveTypeUtil { private static final Map, Class> WRAPPER_TYPE_MAP; @@ -23,16 +19,8 @@ public class PrimitiveTypeUtil { WRAPPER_TYPE_MAP.put(Void.class, void.class); } - public boolean isPrimitiveTypeByCommonsLang(Object source) { - return ClassUtils.isPrimitiveOrWrapper(source.getClass()); - } - - public boolean isPrimitiveTypeByGuava(Object source) { - return Primitives.isWrapperType(source.getClass()); - } - - public boolean isPrimitiveType(Object source) { - return WRAPPER_TYPE_MAP.containsKey(source.getClass()); + public boolean isPrimitiveType(Class sourceClass) { + return WRAPPER_TYPE_MAP.containsKey(sourceClass); } } diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java new file mode 100644 index 0000000000..5bbededbb3 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.primitivetype; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.lang3.ClassUtils; +import org.junit.Before; +import org.junit.Test; + +import com.google.common.primitives.Primitives; + +public class PrimitiveTypeUnitTest { + + private PrimitiveTypeUtil primitiveTypeUtil; + + @Before + public void setup() { + primitiveTypeUtil = new PrimitiveTypeUtil(); + } + + @Test + public void givenAClass_whenCheckWithPrimitiveTypeUtil_thenShouldValidate() { + assertTrue(primitiveTypeUtil.isPrimitiveType(Boolean.class)); + assertFalse(primitiveTypeUtil.isPrimitiveType(String.class)); + } + + @Test + public void givenAClass_whenCheckWithCommonsLang_thenShouldValidate() { + assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.class)); + assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class)); + assertFalse(ClassUtils.isPrimitiveOrWrapper(String.class)); + } + + @Test + public void givenAClass_whenCheckWithGuava_thenShouldValidate() { + assertTrue(Primitives.isWrapperType(Boolean.class)); + assertFalse(Primitives.isWrapperType(String.class)); + assertFalse(Primitives.isWrapperType(boolean.class)); + } +} diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java deleted file mode 100644 index 5cd1b9f9d7..0000000000 --- a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUtilUnitTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.primitivetype; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -public class PrimitiveTypeUtilUnitTest { - - private PrimitiveTypeUtil primitiveTypeUtil; - private boolean booleanVal = false; - private Long longWrapper = 1L; - private String nonPrimitiveVal = "non primitive string"; - - @Before - public void setup() { - primitiveTypeUtil = new PrimitiveTypeUtil(); - } - - @Test - public void givenObjectWhenCheckWithGuavaShouldValidate() { - assertTrue(primitiveTypeUtil.isPrimitiveTypeByGuava(booleanVal)); - assertTrue(primitiveTypeUtil.isPrimitiveTypeByGuava(longWrapper)); - assertFalse(primitiveTypeUtil.isPrimitiveTypeByGuava(nonPrimitiveVal)); - } - - @Test - public void givenObjectWhenCheckWithCommonsLangShouldValidate() { - assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommonsLang(booleanVal)); - assertTrue(primitiveTypeUtil.isPrimitiveTypeByCommonsLang(longWrapper)); - assertFalse(primitiveTypeUtil.isPrimitiveTypeByCommonsLang(nonPrimitiveVal)); - } - - @Test - public void givenPrimitiveOrWrapperWhenCheckWithCustomMethodShouldReturnTrue() { - assertTrue(primitiveTypeUtil.isPrimitiveType(booleanVal)); - assertTrue(primitiveTypeUtil.isPrimitiveType(longWrapper)); - assertFalse(primitiveTypeUtil.isPrimitiveType(nonPrimitiveVal)); - } -} From a27969cc707f4883f2737027cf0240ebce2d06ae Mon Sep 17 00:00:00 2001 From: Umang Budhwar Date: Mon, 3 Aug 2020 21:01:57 +0530 Subject: [PATCH 131/155] Refactored code to use existing variables. --- .../SetFieldsUsingReflectionUnitTest.java | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java index 8931d22160..3fe6994041 100644 --- a/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java +++ b/core-java-modules/core-java-reflection-2/src/test/java/com/baeldung/reflection/set/fields/SetFieldsUsingReflectionUnitTest.java @@ -19,7 +19,7 @@ public class SetFieldsUsingReflectionUnitTest { byte age = 26; ageField.setByte(person, age); - Assertions.assertEquals(26, person.getAge()); + Assertions.assertEquals(age, person.getAge()); Field uidNumberField = person.getClass() .getDeclaredField("uidNumber"); @@ -27,7 +27,7 @@ public class SetFieldsUsingReflectionUnitTest { short uidNumber = 5555; uidNumberField.setShort(person, uidNumber); - Assertions.assertEquals(5555, person.getUidNumber()); + Assertions.assertEquals(uidNumber, person.getUidNumber()); Field pinCodeField = person.getClass() .getDeclaredField("pinCode"); @@ -35,7 +35,7 @@ public class SetFieldsUsingReflectionUnitTest { int pinCode = 411057; pinCodeField.setInt(person, pinCode); - Assertions.assertEquals(411057, person.getPinCode()); + Assertions.assertEquals(pinCode, person.getPinCode()); Field contactNumberField = person.getClass() .getDeclaredField("contactNumber"); @@ -43,7 +43,7 @@ public class SetFieldsUsingReflectionUnitTest { long contactNumber = 123456789L; contactNumberField.setLong(person, contactNumber); - Assertions.assertEquals(123456789L, person.getContactNumber()); + Assertions.assertEquals(contactNumber, person.getContactNumber()); } @@ -57,7 +57,7 @@ public class SetFieldsUsingReflectionUnitTest { Integer pinCode = 411057; pinCodeField.setInt(person, pinCode); - Assertions.assertEquals(411057, person.getPinCode()); + Assertions.assertEquals(pinCode, person.getPinCode()); } @Test @@ -70,7 +70,7 @@ public class SetFieldsUsingReflectionUnitTest { short pinCode = 4110; pinCodeField.setInt(person, pinCode); - Assertions.assertEquals(4110, person.getPinCode()); + Assertions.assertEquals(pinCode, person.getPinCode()); } @Test @@ -83,7 +83,7 @@ public class SetFieldsUsingReflectionUnitTest { float height = 6.1242f; heightField.setFloat(person, height); - Assertions.assertEquals(6.1242f, person.getHeight()); + Assertions.assertEquals(height, person.getHeight()); Field weightField = person.getClass() .getDeclaredField("weight"); @@ -91,7 +91,7 @@ public class SetFieldsUsingReflectionUnitTest { double weight = 75.2564; weightField.setDouble(person, weight); - Assertions.assertEquals(75.2564, person.getWeight()); + Assertions.assertEquals(weight, person.getWeight()); } @Test @@ -104,7 +104,7 @@ public class SetFieldsUsingReflectionUnitTest { char gender = 'M'; genderField.setChar(person, gender); - Assertions.assertEquals('M', person.getGender()); + Assertions.assertEquals(gender, person.getGender()); } @Test @@ -115,8 +115,7 @@ public class SetFieldsUsingReflectionUnitTest { .getDeclaredField("active"); activeField.setAccessible(true); - boolean active = true; - activeField.setBoolean(person, active); + activeField.setBoolean(person, true); Assertions.assertTrue(person.isActive()); } @@ -130,7 +129,7 @@ public class SetFieldsUsingReflectionUnitTest { String name = "Umang Budhwar"; nameField.set(person, name); - Assertions.assertEquals("Umang Budhwar", person.getName()); + Assertions.assertEquals(name, person.getName()); } @Test From e7ec3ff7bcfd8114b83aae8bb40735bd9bb90f14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Dupire?= Date: Wed, 5 Aug 2020 03:45:26 +0200 Subject: [PATCH 132/155] [JAVA-2276] Disabled frontend-maven-plugin for default-first and default-second profiles (#9820) * [JAVA-2276] Upgraded maven-assembly-plugin version to 3.3.0 * [JAVA-2276] Disabling frontend-maven-plugin for default-first and default-second profiles --- jhipster-5/bookstore-monolith/pom.xml | 62 +++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index 4e4c82f327..03395e47ed 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -1008,6 +1008,68 @@ + + default-first + + + + + com.github.eirslett + frontend-maven-plugin + + + + install node and npm + none + + + npm install + none + + + webpack build dev + none + + + webpack build test + none + + + + + + + + default-second + + + + + com.github.eirslett + frontend-maven-plugin + + + + install node and npm + none + + + npm install + none + + + webpack build dev + none + + + webpack build test + none + + + + + + From 4367410910e05cf1ad513bff1f720b6d55069eb3 Mon Sep 17 00:00:00 2001 From: Jordan Simpson Date: Wed, 5 Aug 2020 10:47:13 -0500 Subject: [PATCH 133/155] Added pom packaging to module's pom --- maven-modules/optional-dependencies/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/maven-modules/optional-dependencies/pom.xml b/maven-modules/optional-dependencies/pom.xml index c1bfc6fb59..12d028b2d7 100644 --- a/maven-modules/optional-dependencies/pom.xml +++ b/maven-modules/optional-dependencies/pom.xml @@ -10,6 +10,7 @@ 4.0.0 optional-dependencies + pom optional-project project-with-optionals From f3740c95c333c5b01c1f8c59f494a1cd43c67eae Mon Sep 17 00:00:00 2001 From: mdhtr Date: Wed, 5 Aug 2020 18:53:22 +0200 Subject: [PATCH 134/155] Make fields private and use getters/setters/constructors instead --- .../JacksonDeserializationUnitTest.java | 12 ++-- .../jsonldjava/jackson/Person.java | 56 +++++++++++++++++-- .../HydraJsonldSerializationUnitTest.java | 4 +- .../serialization/hydrajsonld/Person.java | 17 +++++- .../JacksonJsonLdSerializationUnitTest.java | 2 +- .../serialization/jacksonjsonld/Person.java | 17 +++++- 6 files changed, 88 insertions(+), 20 deletions(-) diff --git a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java index 9c6b6f976a..24968f3847 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/JacksonDeserializationUnitTest.java @@ -42,14 +42,10 @@ public class JacksonDeserializationUnitTest { ObjectMapper objectMapper = new ObjectMapper(); Person person = objectMapper.readValue(compactContent, Person.class); - Person expectedPerson = new Person(); - expectedPerson.id = "http://example.com/person/1234"; - expectedPerson.name = "Example Name"; - expectedPerson.knows = new Link(); - expectedPerson.knows.id = "http://example.com/person/2345"; + Person expectedPerson = new Person("http://example.com/person/1234", "Example Name", new Link("http://example.com/person/2345")); - assertEquals(expectedPerson.id, person.id); - assertEquals(expectedPerson.name, person.name); - assertEquals(expectedPerson.knows.id, person.knows.id); + assertEquals(expectedPerson.getId(), person.getId()); + assertEquals(expectedPerson.getName(), person.getName()); + assertEquals(expectedPerson.getKnows().getId(), person.getKnows().getId()); } } diff --git a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java index 0cb6d43336..fefa676817 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java +++ b/json-2/src/test/java/com/baeldung/jsonld/deserialization/jsonldjava/jackson/Person.java @@ -6,14 +6,62 @@ import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Person { @JsonProperty("@id") - public String id; + private String id; @JsonProperty("http://schema.org/name") - public String name; + private String name; @JsonProperty("http://schema.org/knows") - public Link knows; + private Link knows; + + public Person() { + } + + public Person(String id, String name, Link knows) { + this.id = id; + this.name = name; + this.knows = knows; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Link getKnows() { + return knows; + } + + public void setKnows(Link knows) { + this.knows = knows; + } public static class Link { @JsonProperty("@id") - public String id; + private String id; + + public Link() { + } + + public Link(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } } } diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java index 06105d579e..33395cc438 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/HydraJsonldSerializationUnitTest.java @@ -23,9 +23,7 @@ public class HydraJsonldSerializationUnitTest { objectMapper.registerModule(getJacksonHydraSerializerModule()); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - Person person = new Person(); - person.id = "http://example.com/person/1234"; - person.name = "Example Name"; + Person person = new Person("http://example.com/person/1234", "Example Name"); String personJsonLd = objectMapper.writeValueAsString(person); diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java index 87587d02ac..3d8573c965 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/hydrajsonld/Person.java @@ -8,8 +8,21 @@ import de.escalon.hypermedia.hydra.mapping.Vocab; @Vocab("http://example.com/vocab/") @Expose("person") public class Person { + private String id; + private String name; + + public Person(String id, String name) { + this.id = id; + this.name = name; + } + @JsonProperty("@id") - public String id; + public String getId() { + return id; + } + @Expose("fullName") - public String name; + public String getName() { + return name; + } } diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java index cd41989a53..9679426acb 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/JacksonJsonLdSerializationUnitTest.java @@ -15,7 +15,7 @@ public class JacksonJsonLdSerializationUnitTest { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JsonldModule()); - Person person = new Person(); + Person person = new Person("http://example.com/person/1234", "Example Name"); String personJsonLd = objectMapper.writeValueAsString(person); assertEquals("{" diff --git a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java index d0c9e4f111..b63f49840c 100644 --- a/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java +++ b/json-2/src/test/java/com/baeldung/jsonld/serialization/jacksonjsonld/Person.java @@ -13,7 +13,20 @@ import ioinformarics.oss.jackson.module.jsonld.annotation.JsonldType; @JsonldLink(rel = "s:knows", name = "knows", href = "http://example.com/person/2345") public class Person { @JsonldId - public String id = "http://example.com/person/1234"; + private String id; @JsonldProperty("s:name") - public String name = "Example Name"; + private String name; + + public Person(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } } From 18c7b3000e34bdd847cb1ef3eb8ece9f3d1eca08 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Thu, 6 Aug 2020 00:08:27 +0200 Subject: [PATCH 135/155] BAEL-4405 move probability examples to java-numbers-4 --- java-numbers-4/pom.xml | 52 +++++++++++++++++++ .../probability/MaleHeightGenerator.java | 0 .../baeldung/probability/RandomInvoker.java | 0 .../probability/RandomInvokerUnitTest.java | 0 4 files changed, 52 insertions(+) create mode 100644 java-numbers-4/pom.xml rename {java-numbers-3 => java-numbers-4}/src/main/java/com/baeldung/probability/MaleHeightGenerator.java (100%) rename {java-numbers-3 => java-numbers-4}/src/main/java/com/baeldung/probability/RandomInvoker.java (100%) rename {java-numbers-3 => java-numbers-4}/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java (100%) diff --git a/java-numbers-4/pom.xml b/java-numbers-4/pom.xml new file mode 100644 index 0000000000..e1722fb039 --- /dev/null +++ b/java-numbers-4/pom.xml @@ -0,0 +1,52 @@ + + 4.0.0 + java-numbers-4 + java-numbers-4 + jar + + + com.baeldung + parent-java + 0.0.1-SNAPSHOT + ../parent-java + + + + + io.vavr + vavr + ${vavr.version} + + + org.apache.commons + commons-lang3 + ${commons.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-numbers-4 + + + src/main/resources + true + + + + + + 0.10.2 + 3.9 + 3.6.1 + + + diff --git a/java-numbers-3/src/main/java/com/baeldung/probability/MaleHeightGenerator.java b/java-numbers-4/src/main/java/com/baeldung/probability/MaleHeightGenerator.java similarity index 100% rename from java-numbers-3/src/main/java/com/baeldung/probability/MaleHeightGenerator.java rename to java-numbers-4/src/main/java/com/baeldung/probability/MaleHeightGenerator.java diff --git a/java-numbers-3/src/main/java/com/baeldung/probability/RandomInvoker.java b/java-numbers-4/src/main/java/com/baeldung/probability/RandomInvoker.java similarity index 100% rename from java-numbers-3/src/main/java/com/baeldung/probability/RandomInvoker.java rename to java-numbers-4/src/main/java/com/baeldung/probability/RandomInvoker.java diff --git a/java-numbers-3/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java b/java-numbers-4/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java similarity index 100% rename from java-numbers-3/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java rename to java-numbers-4/src/test/java/com/baeldung/probability/RandomInvokerUnitTest.java From ca8dd7dbc7e56091f554ff98657cb9d7ab67c045 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Thu, 6 Aug 2020 00:11:13 +0200 Subject: [PATCH 136/155] BAEL-4405 better names for parameters --- .../main/java/com/baeldung/probability/RandomInvoker.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java-numbers-4/src/main/java/com/baeldung/probability/RandomInvoker.java b/java-numbers-4/src/main/java/com/baeldung/probability/RandomInvoker.java index 30be5725ab..66f82022ea 100644 --- a/java-numbers-4/src/main/java/com/baeldung/probability/RandomInvoker.java +++ b/java-numbers-4/src/main/java/com/baeldung/probability/RandomInvoker.java @@ -8,12 +8,12 @@ import java.util.function.Supplier; public class RandomInvoker { private final Lazy random = Lazy.of(SplittableRandom::new); - public T withProbability(Supplier supplier1, Supplier supplier2, int probability) { + public T withProbability(Supplier positiveCase, Supplier negativeCase, int probability) { SplittableRandom random = this.random.get(); if (random.nextInt(1, 101) <= probability) { - return supplier1.get(); + return positiveCase.get(); } else { - return supplier2.get(); + return negativeCase.get(); } } } From 54796738f8d478c07358a11802e94715ff729b4b Mon Sep 17 00:00:00 2001 From: joe zhang Date: Thu, 6 Aug 2020 23:14:19 +0800 Subject: [PATCH 137/155] update unit test --- .../primitivetype/PrimitiveTypeUtil.java | 4 ++-- .../primitivetype/PrimitiveTypeUnitTest.java | 24 +++++++------------ 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java index 9607a0008f..ff70da1839 100644 --- a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/primitivetype/PrimitiveTypeUtil.java @@ -19,8 +19,8 @@ public class PrimitiveTypeUtil { WRAPPER_TYPE_MAP.put(Void.class, void.class); } - public boolean isPrimitiveType(Class sourceClass) { - return WRAPPER_TYPE_MAP.containsKey(sourceClass); + public static boolean isPrimitiveType(Object source) { + return WRAPPER_TYPE_MAP.containsKey(source.getClass()); } } diff --git a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java index 5bbededbb3..b9152d3674 100644 --- a/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java +++ b/core-java-modules/core-java-lang-oop-types/src/test/java/com/baeldung/primitivetype/PrimitiveTypeUnitTest.java @@ -4,37 +4,31 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.apache.commons.lang3.ClassUtils; -import org.junit.Before; +import org.apache.commons.lang3.StringUtils; import org.junit.Test; import com.google.common.primitives.Primitives; public class PrimitiveTypeUnitTest { - private PrimitiveTypeUtil primitiveTypeUtil; - - @Before - public void setup() { - primitiveTypeUtil = new PrimitiveTypeUtil(); - } - @Test public void givenAClass_whenCheckWithPrimitiveTypeUtil_thenShouldValidate() { - assertTrue(primitiveTypeUtil.isPrimitiveType(Boolean.class)); - assertFalse(primitiveTypeUtil.isPrimitiveType(String.class)); + assertTrue(PrimitiveTypeUtil.isPrimitiveType(false)); + assertTrue(PrimitiveTypeUtil.isPrimitiveType(1L)); + assertFalse(PrimitiveTypeUtil.isPrimitiveType(StringUtils.EMPTY)); } @Test public void givenAClass_whenCheckWithCommonsLang_thenShouldValidate() { - assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.class)); + assertTrue(ClassUtils.isPrimitiveOrWrapper(Boolean.FALSE.getClass())); assertTrue(ClassUtils.isPrimitiveOrWrapper(boolean.class)); - assertFalse(ClassUtils.isPrimitiveOrWrapper(String.class)); + assertFalse(ClassUtils.isPrimitiveOrWrapper(StringUtils.EMPTY.getClass())); } @Test public void givenAClass_whenCheckWithGuava_thenShouldValidate() { - assertTrue(Primitives.isWrapperType(Boolean.class)); - assertFalse(Primitives.isWrapperType(String.class)); - assertFalse(Primitives.isWrapperType(boolean.class)); + assertTrue(Primitives.isWrapperType(Boolean.FALSE.getClass())); + assertFalse(Primitives.isWrapperType(StringUtils.EMPTY.getClass())); + assertFalse(Primitives.isWrapperType(Boolean.TYPE.getClass())); } } From d444ab4d54a8aed35cc6be8cc5731df98d7388f7 Mon Sep 17 00:00:00 2001 From: karan Date: Thu, 6 Aug 2020 13:40:44 -0400 Subject: [PATCH 138/155] Fix formatting --- .../PathVariableAnnotationController.java | 136 +++++++++--------- 1 file changed, 68 insertions(+), 68 deletions(-) diff --git a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java index 37e104f354..0cbd852095 100644 --- a/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java +++ b/spring-mvc-java-2/src/main/java/com/baeldung/pathvariable/PathVariableAnnotationController.java @@ -10,80 +10,80 @@ import java.util.Optional; @RestController public class PathVariableAnnotationController { - @GetMapping("/api/employees/{id}") - @ResponseBody - public String getEmployeesById(@PathVariable String id) { - return "ID: " + id; - } + @GetMapping("/api/employees/{id}") + @ResponseBody + public String getEmployeesById(@PathVariable String id) { + return "ID: " + id; + } - @GetMapping("/api/employeeswithvariable/{id}") - @ResponseBody - public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) { - return "ID: " + employeeId; - } + @GetMapping("/api/employeeswithvariable/{id}") + @ResponseBody + public String getEmployeesByIdWithVariableName(@PathVariable("id") String employeeId) { + return "ID: " + employeeId; + } - @GetMapping("/api/employees/{id}/{name}") - @ResponseBody - public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) { - return "ID: " + id + ", name: " + name; - } + @GetMapping("/api/employees/{id}/{name}") + @ResponseBody + public String getEmployeesByIdAndName(@PathVariable String id, @PathVariable String name) { + return "ID: " + id + ", name: " + name; + } - @GetMapping("/api/employeeswithmapvariable/{id}/{name}") - @ResponseBody - public String getEmployeesByIdAndNameWithMapVariable(@PathVariable Map pathVarsMap) { - String id = pathVarsMap.get("id"); - String name = pathVarsMap.get("name"); - if (id != null && name != null) { - return "ID: " + id + ", name: " + name; - } else { - return "Missing Parameters"; - } - } + @GetMapping("/api/employeeswithmapvariable/{id}/{name}") + @ResponseBody + public String getEmployeesByIdAndNameWithMapVariable(@PathVariable Map pathVarsMap) { + String id = pathVarsMap.get("id"); + String name = pathVarsMap.get("name"); + if (id != null && name != null) { + return "ID: " + id + ", name: " + name; + } else { + return "Missing Parameters"; + } + } - @GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" }) - @ResponseBody - public String getEmployeesByIdWithRequired(@PathVariable String id) { - return "ID: " + id; - } + @GetMapping(value = { "/api/employeeswithrequired", "/api/employeeswithrequired/{id}" }) + @ResponseBody + public String getEmployeesByIdWithRequired(@PathVariable String id) { + return "ID: " + id; + } - @GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" }) - @ResponseBody - public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) { - if (id != null) { - return "ID: " + id; - } else { - return "ID missing"; - } - } + @GetMapping(value = { "/api/employeeswithrequiredfalse", "/api/employeeswithrequiredfalse/{id}" }) + @ResponseBody + public String getEmployeesByIdWithRequiredFalse(@PathVariable(required = false) String id) { + if (id != null) { + return "ID: " + id; + } else { + return "ID missing"; + } + } - @GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" }) - @ResponseBody - public String getEmployeesByIdWithOptional(@PathVariable Optional id) { - if (id.isPresent()) { - return "ID: " + id.get(); - } else { - return "ID missing"; - } - } + @GetMapping(value = { "/api/employeeswithoptional", "/api/employeeswithoptional/{id}" }) + @ResponseBody + public String getEmployeesByIdWithOptional(@PathVariable Optional id) { + if (id.isPresent()) { + return "ID: " + id.get(); + } else { + return "ID missing"; + } + } - @GetMapping(value = { "/api/defaultemployeeswithoptional", "/api/defaultemployeeswithoptional/{id}" }) - @ResponseBody - public String getDefaultEmployeesByIdWithOptional(@PathVariable Optional id) { - if (id.isPresent()) { - return "ID: " + id.get(); - } else { - return "ID: Default Employee"; - } - } + @GetMapping(value = { "/api/defaultemployeeswithoptional", "/api/defaultemployeeswithoptional/{id}" }) + @ResponseBody + public String getDefaultEmployeesByIdWithOptional(@PathVariable Optional id) { + if (id.isPresent()) { + return "ID: " + id.get(); + } else { + return "ID: Default Employee"; + } + } - @GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" }) - @ResponseBody - public String getEmployeesByIdWithMap(@PathVariable Map pathVarsMap) { - String id = pathVarsMap.get("id"); - if (id != null) { - return "ID: " + id; - } else { - return "ID missing"; - } - } + @GetMapping(value = { "/api/employeeswithmap/{id}", "/api/employeeswithmap" }) + @ResponseBody + public String getEmployeesByIdWithMap(@PathVariable Map pathVarsMap) { + String id = pathVarsMap.get("id"); + if (id != null) { + return "ID: " + id; + } else { + return "ID missing"; + } + } } From d821719314e3d86cacb5bbb43eedb36fb5890e3e Mon Sep 17 00:00:00 2001 From: kwoyke Date: Thu, 6 Aug 2020 21:23:59 +0200 Subject: [PATCH 139/155] BAEL-4492: Use the prefered List.toArray() approach (#9831) --- .../java/collections/JavaCollectionConversionUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java index 4977c122e7..2fd31ab609 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java @@ -32,7 +32,7 @@ public class JavaCollectionConversionUnitTest { @Test public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() { final List sourceList = Arrays.asList(0, 1, 2, 3, 4, 5); - final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]); + final Integer[] targetArray = sourceList.toArray(new Integer[0]); } @Test From fce53395e1ab473bbf486e68ac33bf927cc16fbf Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 7 Aug 2020 03:00:34 +0430 Subject: [PATCH 140/155] Applying TRW Blocks --- .../java/com/baeldung/jdbc/JdbcLiveTest.java | 44 ++++++++----------- 1 file changed, 18 insertions(+), 26 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java index da0c6bffe5..89fd3af864 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java @@ -1,26 +1,18 @@ package com.baeldung.jdbc; -import static org.junit.Assert.*; - -import java.sql.CallableStatement; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.sql.Types; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; - import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + public class JdbcLiveTest { private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class); @@ -33,10 +25,11 @@ public class JdbcLiveTest { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDb?noAccessToProcedureBodies=true", "user1", "pass"); - Statement stmt = con.createStatement(); + try (Statement stmt = con.createStatement()) { - String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; - stmt.execute(tableSql); + String tableSql = "CREATE TABLE IF NOT EXISTS employees (emp_id int PRIMARY KEY AUTO_INCREMENT, name varchar(30), position varchar(30), salary double)"; + stmt.execute(tableSql); + } } @@ -101,10 +94,8 @@ public class JdbcLiveTest { @Test public void whenCallProcedure_thenCorrect() { - - try { - String preparedSql = "{call insertEmployee(?,?,?,?)}"; - CallableStatement cstmt = con.prepareCall(preparedSql); + String preparedSql = "{call insertEmployee(?,?,?,?)}"; + try(CallableStatement cstmt = con.prepareCall(preparedSql)) { cstmt.setString(2, "ana"); cstmt.setString(3, "tester"); cstmt.setDouble(4, 2000); @@ -121,9 +112,10 @@ public class JdbcLiveTest { public void whenReadMetadata_thenCorrect() throws SQLException { DatabaseMetaData dbmd = con.getMetaData(); - ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null); - while (tablesResultSet.next()) { - LOG.info(tablesResultSet.getString("TABLE_NAME")); + try (ResultSet tablesResultSet = dbmd.getTables(null, null, "%", null)) { + while (tablesResultSet.next()) { + LOG.info(tablesResultSet.getString("TABLE_NAME")); + } } String selectSql = "SELECT * FROM employees"; From 2ca30645e8c95d1d0acd4db2573247adea883da3 Mon Sep 17 00:00:00 2001 From: Ali Dehghani Date: Fri, 7 Aug 2020 03:04:25 +0430 Subject: [PATCH 141/155] Polish --- .../test/java/com/baeldung/jdbc/JdbcLiveTest.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java index 89fd3af864..81179aade9 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java @@ -5,7 +5,16 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.sql.*; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Types; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; @@ -95,7 +104,7 @@ public class JdbcLiveTest { @Test public void whenCallProcedure_thenCorrect() { String preparedSql = "{call insertEmployee(?,?,?,?)}"; - try(CallableStatement cstmt = con.prepareCall(preparedSql)) { + try (CallableStatement cstmt = con.prepareCall(preparedSql)) { cstmt.setString(2, "ana"); cstmt.setString(3, "tester"); cstmt.setDouble(4, 2000); From 1b2f33e4d43cde6e3a411f0ada73dc398a94bffe Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Fri, 7 Aug 2020 20:55:22 +0200 Subject: [PATCH 142/155] BAEL-4405 add java-numbers-4 to main pom --- pom.xml | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/pom.xml b/pom.xml index 1db715147a..6b8e69080f 100644 --- a/pom.xml +++ b/pom.xml @@ -343,18 +343,18 @@ animal-sniffer-mvn-plugin annotations antlr - - apache-cxf - apache-libraries - apache-olingo/olingo2 - apache-poi + + apache-cxf + apache-libraries + apache-olingo/olingo2 + apache-poi apache-rocketmq - apache-shiro + apache-shiro apache-spark apache-tapestry apache-thrift apache-tika - apache-velocity + apache-velocity asciidoctor asm @@ -448,7 +448,8 @@ java-lite java-numbers java-numbers-2 - java-numbers-3 + java-numbers-3 + java-numbers-4 java-rmi java-spi java-vavr-stream @@ -858,18 +859,18 @@ animal-sniffer-mvn-plugin annotations antlr - - apache-cxf - apache-libraries - apache-olingo/olingo2 - apache-poi + + apache-cxf + apache-libraries + apache-olingo/olingo2 + apache-poi apache-rocketmq - apache-shiro + apache-shiro apache-spark apache-tapestry apache-thrift apache-tika - apache-velocity + apache-velocity asciidoctor asm @@ -962,6 +963,7 @@ java-numbers java-numbers-2 java-numbers-3 + java-numbers-4 java-rmi java-spi java-vavr-stream From c5326ca2e81eb37864b4afb802df6e6815faceef Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:02:52 +0530 Subject: [PATCH 143/155] BAEL-4408 Adding files for BAEL-4408 --- .../src/main/webapp/WEB-INF/jsp/main.jsp | 15 +++++++++++++++ .../src/main/webapp/WEB-INF/jsp/update.jsp | 17 +++++++++++++++++ .../src/main/webapp/WEB-INF/jsp/userlogin.jsp | 18 ++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 javax-servlets/src/main/webapp/WEB-INF/jsp/main.jsp create mode 100644 javax-servlets/src/main/webapp/WEB-INF/jsp/update.jsp create mode 100644 javax-servlets/src/main/webapp/WEB-INF/jsp/userlogin.jsp diff --git a/javax-servlets/src/main/webapp/WEB-INF/jsp/main.jsp b/javax-servlets/src/main/webapp/WEB-INF/jsp/main.jsp new file mode 100644 index 0000000000..cbbb578770 --- /dev/null +++ b/javax-servlets/src/main/webapp/WEB-INF/jsp/main.jsp @@ -0,0 +1,15 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + + + +
+

Enter your User Id and Password

+ User ID:
+ Password:
+
+ + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/WEB-INF/jsp/update.jsp b/javax-servlets/src/main/webapp/WEB-INF/jsp/update.jsp new file mode 100644 index 0000000000..36ac2d277b --- /dev/null +++ b/javax-servlets/src/main/webapp/WEB-INF/jsp/update.jsp @@ -0,0 +1,17 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + + + + + Hi, User : ${sessionData.getAttribute("userId")} + +
Your User Data has been updated as below : +
User Name: ${sessionData.getAttribute("userName")} +
Age : ${sessionData.getAttribute("age")} + + + \ No newline at end of file diff --git a/javax-servlets/src/main/webapp/WEB-INF/jsp/userlogin.jsp b/javax-servlets/src/main/webapp/WEB-INF/jsp/userlogin.jsp new file mode 100644 index 0000000000..f181222f39 --- /dev/null +++ b/javax-servlets/src/main/webapp/WEB-INF/jsp/userlogin.jsp @@ -0,0 +1,18 @@ +<%@ page language="java" contentType="text/html; charset=ISO-8859-1" + pageEncoding="ISO-8859-1"%> + + + + + + +

Update your User Details:

+ +
+ User ID:
User Name: + Age:
+
+ + \ No newline at end of file From b81350cfae15e523f9673c410182e68ce6f858aa Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:05:45 +0530 Subject: [PATCH 144/155] BAEL-4408 BAEL-4408 files added --- .../com/baeldung/servlets/MainServlet.java | 22 ++++++++++++++ .../com/baeldung/servlets/UpdateServlet.java | 30 +++++++++++++++++++ .../baeldung/servlets/UserLoginServlet.java | 30 +++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 javax-servlets/src/main/java/com/baeldung/servlets/MainServlet.java create mode 100644 javax-servlets/src/main/java/com/baeldung/servlets/UpdateServlet.java create mode 100644 javax-servlets/src/main/java/com/baeldung/servlets/UserLoginServlet.java diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/MainServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/MainServlet.java new file mode 100644 index 0000000000..d4417b0b4e --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/MainServlet.java @@ -0,0 +1,22 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebServlet("/main") +public class MainServlet extends HttpServlet { + + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + response.sendRedirect("main.jsp"); + } + + + + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UpdateServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UpdateServlet.java new file mode 100644 index 0000000000..d0404d0cd4 --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UpdateServlet.java @@ -0,0 +1,30 @@ +package com.baeldung.servlets; + + +import java.io.IOException; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@WebServlet("/update") +public class UpdateServlet extends HttpServlet { + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + HttpSession session = request.getSession(false); + + session.setAttribute("userName", request.getParameter("userName")); + session.setAttribute("age", request.getParameter("age")); + + request.setAttribute("sessionData", session); + RequestDispatcher requestDispather = request.getRequestDispatcher("update.jsp"); + + requestDispather.forward(request, response); + } + +} diff --git a/javax-servlets/src/main/java/com/baeldung/servlets/UserLoginServlet.java b/javax-servlets/src/main/java/com/baeldung/servlets/UserLoginServlet.java new file mode 100644 index 0000000000..6becf04a0c --- /dev/null +++ b/javax-servlets/src/main/java/com/baeldung/servlets/UserLoginServlet.java @@ -0,0 +1,30 @@ +package com.baeldung.servlets; + + +import java.io.IOException; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +@WebServlet("/u_login") +public class UserLoginServlet extends HttpServlet { + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(); + + session.setAttribute("userId", request.getParameter("userId")); + + request.setAttribute("id", session.getAttribute("userId")); + + RequestDispatcher requestDispather = request.getRequestDispatcher("userlogin.jsp"); + + requestDispather.forward(request, response); + + } + +} From 93bbd7881c09ea97c91cdcced2cae6cbbf920f97 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:06:35 +0530 Subject: [PATCH 145/155] README.md updated with BAEL-4408 --- javax-servlets/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/javax-servlets/README.md b/javax-servlets/README.md index 7dbe1a02ad..54f92064a0 100644 --- a/javax-servlets/README.md +++ b/javax-servlets/README.md @@ -12,3 +12,4 @@ This module contains articles about Servlets. - [Jakarta EE Servlet Exception Handling](https://www.baeldung.com/servlet-exceptions) - [Context and Servlet Initialization Parameters](https://www.baeldung.com/context-servlet-initialization-param) - [The Difference between getRequestURI and getPathInfo in HttpServletRequest](https://www.baeldung.com/http-servlet-request-requesturi-pathinfo) +- Difference between request.getSession() and request.getSession(true) From a904f90ffcc1b0678236313cebf06d4b8994c008 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:10:20 +0530 Subject: [PATCH 146/155] Delete FirstServlet.java --- .../baeldung/httpsession/FirstServlet.java | 33 ------------------- 1 file changed, 33 deletions(-) delete mode 100644 spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java diff --git a/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java b/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java deleted file mode 100644 index 950bea2c07..0000000000 --- a/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/FirstServlet.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.httpsession; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -public class FirstServlet extends HttpServlet { - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - try { - HttpSession session = request.getSession(); - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - - String name = request.getParameter("userName"); - session.setAttribute("uname", name); - out.println("Hi " + name + " Your Session Id is : " + session.getId() + " "); - - out.println("
Second Servlet"); - - out.close(); - - } catch (Exception e) { - System.out.println(e); - } - } - -} From 2db04e302f98867c2902a5dc26fcddcfe4af74b6 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:10:35 +0530 Subject: [PATCH 147/155] Delete SecondServlet.java --- .../baeldung/httpsession/SecondServlet.java | 31 ------------------- 1 file changed, 31 deletions(-) delete mode 100644 spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java diff --git a/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java b/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java deleted file mode 100644 index 6a5ef7e9a8..0000000000 --- a/spring-session/http-session-example/src/main/java/com/baeldung/httpsession/SecondServlet.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.baeldung.httpsession; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -public class SecondServlet extends HttpServlet { - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - try { - - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - - HttpSession session = request.getSession(true); - String name = (String) session.getAttribute("uname"); - out.println("Hi " + name + " Your Session Id is : " + session.getId()); - - out.close(); - - } catch (Exception e) { - System.out.println(e); - } - } - -} From 3c3b38df33f1102f6c7b9cb632096f6d4adb0d1d Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:11:04 +0530 Subject: [PATCH 148/155] Delete index.html --- .../http-session-example/src/main/webapp/index.html | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 spring-session/http-session-example/src/main/webapp/index.html diff --git a/spring-session/http-session-example/src/main/webapp/index.html b/spring-session/http-session-example/src/main/webapp/index.html deleted file mode 100644 index 0e5889f21a..0000000000 --- a/spring-session/http-session-example/src/main/webapp/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - -
- Name:

-
- - \ No newline at end of file From efac1811a34ca78fcb1320a123bfa07761fc03dc Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:11:30 +0530 Subject: [PATCH 149/155] Delete web.xml --- .../src/main/webapp/WEB-INF/web.xml | 33 ------------------- 1 file changed, 33 deletions(-) delete mode 100644 spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml diff --git a/spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml b/spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 2c9a4c118b..0000000000 --- a/spring-session/http-session-example/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - httpsession - - index.html - - - - - FirstServlet - com.baeldung.httpsession.FirstServlet - - - SecondServlet - com.baeldung.httpsession.SecondServlet - - - - - FirstServlet - /first - - - SecondServlet - /second - - - - \ No newline at end of file From 14d522372d6099aa4e92524cffd89ff0eca92732 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:12:12 +0530 Subject: [PATCH 150/155] Delete README.md --- spring-session/http-session-example/README.md | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 spring-session/http-session-example/README.md diff --git a/spring-session/http-session-example/README.md b/spring-session/http-session-example/README.md deleted file mode 100644 index 95c7a41e2d..0000000000 --- a/spring-session/http-session-example/README.md +++ /dev/null @@ -1,5 +0,0 @@ -## HttpSession - -This module contains article about Difference Between request.getSession() and request.getSession(true) - -### Relevant Articles: From 257b130ec2667fc18da4eb33a801f284b408f348 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:12:25 +0530 Subject: [PATCH 151/155] Delete pom.xml --- spring-session/http-session-example/pom.xml | 26 --------------------- 1 file changed, 26 deletions(-) delete mode 100644 spring-session/http-session-example/pom.xml diff --git a/spring-session/http-session-example/pom.xml b/spring-session/http-session-example/pom.xml deleted file mode 100644 index a77176fb4b..0000000000 --- a/spring-session/http-session-example/pom.xml +++ /dev/null @@ -1,26 +0,0 @@ - - 4.0.0 - com.baeldung.httpsession - http-session-example - war - 0.0.1-SNAPSHOT - http-session-example Maven Webapp - http://maven.apache.org - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - javax.servlet - servlet-api - 2.5 - provided - - - From 82651842c78debe7be84f9101c529d6ac1ff4477 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:13:05 +0530 Subject: [PATCH 152/155] Update README.md Removing BAEL-4408 from Readme.md --- spring-session/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-session/README.md b/spring-session/README.md index 47125a6032..65040ec734 100644 --- a/spring-session/README.md +++ b/spring-session/README.md @@ -6,4 +6,3 @@ This module contains articles about Spring Session - [Guide to Spring Session](https://www.baeldung.com/spring-session) - [Spring Session with JDBC](https://www.baeldung.com/spring-session-jdbc) - [Spring Session with MongoDB](https://www.baeldung.com/spring-session-mongodb) -- Difference Between request.getSession() and request.getSession(true) From 5e0e587888663d5972cd556707290901e64d1ce0 Mon Sep 17 00:00:00 2001 From: gupta-ashu01 <30566001+gupta-ashu01@users.noreply.github.com> Date: Sat, 8 Aug 2020 15:15:01 +0530 Subject: [PATCH 153/155] Update pom.xml Removing BAEL-4408 module from pom --- spring-session/pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index d5dbe28a2b..6616a0d1f3 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -19,7 +19,6 @@ spring-session-jdbc spring-session-redis spring-session-mongodb - http-session-example
From 15e94bb577c8895f1ed720284c95c3b3a0609da5 Mon Sep 17 00:00:00 2001 From: Rando Shtishi <42577665+rshtishi@users.noreply.github.com> Date: Sat, 8 Aug 2020 22:21:57 +0200 Subject: [PATCH 154/155] BAEL-4230 - Adding Introduction to Spring Data JDBC Project (#9665) --- persistence-modules/pom.xml | 4 ++ persistence-modules/spring-data-jdbc/pom.xml | 29 +++++++++ .../springdatajdbcintro/Application.java | 59 +++++++++++++++++++ .../springdatajdbcintro/DatabaseSeeder.java | 26 ++++++++ .../springdatajdbcintro/entity/Person.java | 57 ++++++++++++++++++ .../repository/PersonRepository.java | 23 ++++++++ .../src/main/resources/application.properties | 8 +++ .../src/main/resources/schema.sql | 5 ++ pom.xml | 2 +- 9 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 persistence-modules/spring-data-jdbc/pom.xml create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/DatabaseSeeder.java create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java create mode 100644 persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java create mode 100644 persistence-modules/spring-data-jdbc/src/main/resources/application.properties create mode 100644 persistence-modules/spring-data-jdbc/src/main/resources/schema.sql diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 31b9aaaf6d..78f1afd39a 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -59,12 +59,16 @@ spring-data-elasticsearch spring-data-gemfire spring-data-geode + spring-data-jpa-annotations spring-data-jpa-crud spring-data-jpa-enterprise spring-data-jpa-filtering spring-data-jpa-query spring-data-jpa-repo + + spring-data-jdbc + spring-data-keyvalue spring-data-mongodb spring-data-neo4j diff --git a/persistence-modules/spring-data-jdbc/pom.xml b/persistence-modules/spring-data-jdbc/pom.xml new file mode 100644 index 0000000000..ff034104d7 --- /dev/null +++ b/persistence-modules/spring-data-jdbc/pom.xml @@ -0,0 +1,29 @@ + + 4.0.0 + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + spring-data-jdbc + spring-data-jdbc + + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + com.h2database + h2 + runtime + + + diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java new file mode 100644 index 0000000000..7f50aa87f1 --- /dev/null +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/Application.java @@ -0,0 +1,59 @@ +package com.baeldung.springdatajdbcintro; + +import java.util.Optional; + +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import com.baeldung.springdatajdbcintro.entity.Person; +import com.baeldung.springdatajdbcintro.repository.PersonRepository; + +import ch.qos.logback.classic.Logger; + +@SpringBootApplication +public class Application implements CommandLineRunner { + + private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(Application.class); + + @Autowired + private PersonRepository repository; + @Autowired + private DatabaseSeeder dbSeeder; + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Override + public void run(String... arg0) throws Exception { + + LOGGER.info("@@ Inserting Data...."); + dbSeeder.insertData(); + LOGGER.info("@@ findAll() call..."); + repository.findAll() + .forEach(person -> LOGGER.info(person.toString())); + LOGGER.info("@@ findById() call..."); + Optional optionalPerson = repository.findById(1L); + optionalPerson.ifPresent(person -> LOGGER.info(person.toString())); + LOGGER.info("@@ save() call..."); + Person newPerson = new Person("Franz", "Kafka"); + Person result = repository.save(newPerson); + LOGGER.info(result.toString()); + LOGGER.info("@@ delete"); + optionalPerson.ifPresent(person -> repository.delete(person)); + LOGGER.info("@@ findAll() call..."); + repository.findAll() + .forEach(person -> LOGGER.info(person.toString())); + LOGGER.info("@@ findByFirstName() call..."); + repository.findByFirstName("Franz") + .forEach(person -> LOGGER.info(person.toString())); + LOGGER.info("@@ findByFirstName() call..."); + repository.updateByFirstName(2L, "Date Inferno"); + repository.findAll() + .forEach(person -> LOGGER.info(person.toString())); + + } +} diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/DatabaseSeeder.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/DatabaseSeeder.java new file mode 100644 index 0000000000..97055fd7ac --- /dev/null +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/DatabaseSeeder.java @@ -0,0 +1,26 @@ +package com.baeldung.springdatajdbcintro; + +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import ch.qos.logback.classic.Logger; + +@Component +public class DatabaseSeeder { + + private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(DatabaseSeeder.class); + + @Autowired + private JdbcTemplate jdbcTemplate; + + public void insertData() { + LOGGER.info("> Inserting data..."); + jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Victor', 'Hygo')"); + jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Dante', 'Alighieri')"); + jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Stefan', 'Zweig')"); + jdbcTemplate.execute("INSERT INTO Person(first_name,last_name) VALUES('Oscar', 'Wilde')"); + } + +} diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java new file mode 100644 index 0000000000..7c4c1eec73 --- /dev/null +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/entity/Person.java @@ -0,0 +1,57 @@ +package com.baeldung.springdatajdbcintro.entity; + +import org.springframework.data.annotation.Id; + +public class Person { + + @Id + private long id; + private String firstName; + private String lastName; + + public Person() { + super(); + } + + public Person(long id, String firstName, String lastName) { + super(); + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + @Override + public String toString() { + return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; + } + +} diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java new file mode 100644 index 0000000000..2f2329caec --- /dev/null +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java @@ -0,0 +1,23 @@ +package com.baeldung.springdatajdbcintro.repository; + +import java.util.List; + +import org.springframework.data.jdbc.repository.query.Modifying; +import org.springframework.data.jdbc.repository.query.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +import com.baeldung.springdatajdbcintro.entity.Person; + +@Repository +public interface PersonRepository extends CrudRepository { + + @Query("select * from person where first_name=:firstName") + List findByFirstName(@Param("firstName") String firstName); + + @Modifying + @Query("UPDATE person SET first_name = :name WHERE id = :id") + boolean updateByFirstName(@Param("id") Long id, @Param("name") String name); + +} diff --git a/persistence-modules/spring-data-jdbc/src/main/resources/application.properties b/persistence-modules/spring-data-jdbc/src/main/resources/application.properties new file mode 100644 index 0000000000..45099222fc --- /dev/null +++ b/persistence-modules/spring-data-jdbc/src/main/resources/application.properties @@ -0,0 +1,8 @@ +#H2 DB +spring.jpa.hibernate.ddl-auto=none +spring.h2.console.enabled=true +spring.datasource.url=jdbc:h2:mem:persondb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=test +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/persistence-modules/spring-data-jdbc/src/main/resources/schema.sql b/persistence-modules/spring-data-jdbc/src/main/resources/schema.sql new file mode 100644 index 0000000000..5618822bf9 --- /dev/null +++ b/persistence-modules/spring-data-jdbc/src/main/resources/schema.sql @@ -0,0 +1,5 @@ +create table person ( + id integer identity primary key, + first_name varchar(30), + last_name varchar(30) +); \ No newline at end of file diff --git a/pom.xml b/pom.xml index b110cb0fe0..a69ffa2798 100644 --- a/pom.xml +++ b/pom.xml @@ -1407,4 +1407,4 @@ 1.4.197 - + \ No newline at end of file From 87111ea998379a1e94b76304b77f0aabab59cfd5 Mon Sep 17 00:00:00 2001 From: kwoyke Date: Sat, 8 Aug 2020 22:41:01 +0200 Subject: [PATCH 155/155] BAEL-4493: Use the prefered Set.toArray() approach (#9837) --- .../collections/JavaCollectionConversionUnitTest.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java index 2fd31ab609..ba640f3fb2 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/java/collections/JavaCollectionConversionUnitTest.java @@ -72,7 +72,7 @@ public class JavaCollectionConversionUnitTest { @Test public final void givenUsingCoreJava_whenSetConvertedToArray_thenCorrect() { final Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5); - final Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]); + final Integer[] targetArray = sourceSet.toArray(new Integer[0]); } @Test @@ -94,16 +94,10 @@ public class JavaCollectionConversionUnitTest { CollectionUtils.addAll(targetSet, sourceArray); } - @Test - public final void givenUsingCommonsCollections_whenSetConvertedToArray_thenCorrect() { - final Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5); - final Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]); - } - @Test public final void givenUsingCommonsCollections_whenSetConvertedToArrayOfPrimitives_thenCorrect() { final Set sourceSet = Sets.newHashSet(0, 1, 2, 3, 4, 5); - final Integer[] targetArray = sourceSet.toArray(new Integer[sourceSet.size()]); + final Integer[] targetArray = sourceSet.toArray(new Integer[0]); final int[] primitiveTargetArray = ArrayUtils.toPrimitive(targetArray); }