diff --git a/.gitignore b/.gitignore index fe56746dfd..88c5e49808 100644 --- a/.gitignore +++ b/.gitignore @@ -87,4 +87,7 @@ transaction.log apache-cxf/cxf-aegis/baeldung.xml testing-modules/report-*.json -libraries-2/*.db \ No newline at end of file +libraries-2/*.db + +# SDKMan +.sdkmanrc diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index 27768d60fc..e0855155bc 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -74,6 +74,7 @@ maven-assembly-plugin + 3.3.0 package diff --git a/core-java-modules/core-java-11-2/README.md b/core-java-modules/core-java-11-2/README.md new file mode 100644 index 0000000000..f65a043819 --- /dev/null +++ b/core-java-modules/core-java-11-2/README.md @@ -0,0 +1,7 @@ +## Core Java 11 + +This module contains articles about Java 11 core features + +### Relevant articles +- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional) + diff --git a/core-java-modules/core-java-11-2/pom.xml b/core-java-modules/core-java-11-2/pom.xml new file mode 100644 index 0000000000..d20b0f23f0 --- /dev/null +++ b/core-java-modules/core-java-11-2/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + core-java-11-2 + 0.1.0-SNAPSHOT + core-java-11-2 + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../.. + + + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + ${maven.compiler.source.version} + ${maven.compiler.target.version} + + + + + + + 11 + 11 + 3.17.2 + + + diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Modem.java b/core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Modem.java similarity index 100% rename from core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Modem.java rename to core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Modem.java diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java b/core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Person.java similarity index 100% rename from core-java-modules/core-java-optional/src/main/java/com/baeldung/optional/Person.java rename to core-java-modules/core-java-11-2/src/main/java/com/baeldung/optional/Person.java diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java similarity index 96% rename from core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java rename to core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java index 9ef156501b..65b9e22f44 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalChainingUnitTest.java @@ -7,7 +7,9 @@ import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Stream; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class OptionalChainingUnitTest { diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalUnitTest.java similarity index 96% rename from core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java rename to core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalUnitTest.java index de16e9b635..1b0a2d4445 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/optional/OptionalUnitTest.java +++ b/core-java-modules/core-java-11-2/src/test/java/com/baeldung/optional/OptionalUnitTest.java @@ -9,7 +9,9 @@ import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; public class OptionalUnitTest { @@ -262,6 +264,12 @@ public class OptionalUnitTest { .orElseThrow(IllegalArgumentException::new); } + @Test(expected = NoSuchElementException.class) + public void whenNoArgOrElseThrowWorks_thenCorrect() { + String nullName = null; + String name = Optional.ofNullable(nullName).orElseThrow(); + } + public String getMyDefault() { LOG.debug("Getting default value..."); return "Default Value"; diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index bbc4219eaa..2f7f5a6bcf 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -107,7 +107,7 @@ benchmarks 1.22 10.0.0 - 10.0.0 + 3.2.4 diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java new file mode 100644 index 0000000000..7c81142949 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExampleCE.java @@ -0,0 +1,11 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExampleCE { + + public static void main(String[] args) { + + //String array[] = new String[5]; //This will lead to compile-time error at line-8 when uncommented + //array[0] = 2; + } + +} diff --git a/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java new file mode 100644 index 0000000000..ce63fd6605 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/main/java/com/baeldung/array/arraystoreexception/ArrayStoreExceptionExample.java @@ -0,0 +1,16 @@ +package com.baeldung.array.arraystoreexception; + +public class ArrayStoreExceptionExample { + + public static void main(String[] args) { + + try { + Object array[] = new String[5]; + array[0] = 2; + } catch (ArrayStoreException e) { + // handle the exception + } + + } + +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java new file mode 100644 index 0000000000..b5867d15e7 --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/Data.java @@ -0,0 +1,14 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +public class Data { + private String message; + + public void send(String message) { + this.message = message; + } + + public String receive() { + return message; + } +} + diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java new file mode 100644 index 0000000000..ff6b926cdc --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedReceiver.java @@ -0,0 +1,39 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SynchronizedReceiver implements Runnable { + private static Logger log = LoggerFactory.getLogger(SynchronizedReceiver.class); + private final Data data; + private String message; + private boolean illegalMonitorStateExceptionOccurred; + + public SynchronizedReceiver(Data data) { + this.data = data; + } + + @Override + public void run() { + synchronized (data) { + try { + data.wait(); + this.message = data.receive(); + } catch (InterruptedException e) { + log.error("thread was interrupted", e); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + log.error("illegal monitor state exception occurred", e); + illegalMonitorStateExceptionOccurred = true; + } + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } + + public String getMessage() { + return message; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java new file mode 100644 index 0000000000..1618bc8efa --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/SynchronizedSender.java @@ -0,0 +1,37 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SynchronizedSender implements Runnable { + private static Logger log = LoggerFactory.getLogger(SynchronizedSender.class); + private final Data data; + private boolean illegalMonitorStateExceptionOccurred; + + public SynchronizedSender(Data data) { + this.data = data; + } + + @Override + public void run() { + synchronized (data) { + try { + Thread.sleep(1000); + + data.send("test"); + + data.notifyAll(); + } catch (InterruptedException e) { + log.error("thread was interrupted", e); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + log.error("illegal monitor state exception occurred", e); + illegalMonitorStateExceptionOccurred = true; + } + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedReceiver.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedReceiver.java new file mode 100644 index 0000000000..3a0b72e6cd --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedReceiver.java @@ -0,0 +1,37 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UnsynchronizedReceiver implements Runnable { + private static Logger log = LoggerFactory.getLogger(UnsynchronizedReceiver.class); + private final Data data; + private String message; + private boolean illegalMonitorStateExceptionOccurred; + + public UnsynchronizedReceiver(Data data) { + this.data = data; + } + + @Override + public void run() { + try { + data.wait(); + this.message = data.receive(); + } catch (InterruptedException e) { + log.error("thread was interrupted", e); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + log.error("illegal monitor state exception occurred", e); + illegalMonitorStateExceptionOccurred = true; + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } + + public String getMessage() { + return message; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedSender.java b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedSender.java new file mode 100644 index 0000000000..7f15418bfa --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/main/java/com/baeldung/exceptions/illegalmonitorstate/UnsynchronizedSender.java @@ -0,0 +1,35 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UnsynchronizedSender implements Runnable { + private static Logger log = LoggerFactory.getLogger(UnsynchronizedSender.class); + private final Data data; + private boolean illegalMonitorStateExceptionOccurred; + + public UnsynchronizedSender(Data data) { + this.data = data; + } + + @Override + public void run() { + try { + Thread.sleep(1000); + + data.send("test"); + + data.notifyAll(); + } catch (InterruptedException e) { + log.error("thread was interrupted", e); + Thread.currentThread().interrupt(); + } catch (IllegalMonitorStateException e) { + log.error("illegal monitor state exception occurred", e); + illegalMonitorStateExceptionOccurred = true; + } + } + + public boolean hasIllegalMonitorStateExceptionOccurred() { + return illegalMonitorStateExceptionOccurred; + } +} diff --git a/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java new file mode 100644 index 0000000000..a729facdbd --- /dev/null +++ b/core-java-modules/core-java-exceptions-3/src/test/java/com/baeldung/exceptions/illegalmonitorstate/IllegalMonitorStateExceptionUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.exceptions.illegalmonitorstate; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class IllegalMonitorStateExceptionUnitTest { + + @Test + void whenSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException { + Data data = new Data(); + + SynchronizedReceiver receiver = new SynchronizedReceiver(data); + Thread receiverThread = new Thread(receiver, "receiver-thread"); + receiverThread.start(); + + SynchronizedSender sender = new SynchronizedSender(data); + Thread senderThread = new Thread(sender, "sender-thread"); + senderThread.start(); + + senderThread.join(1000); + receiverThread.join(1000); + + assertEquals("test", receiver.getMessage()); + assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); + assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); + } + + @Test + void whenSyncSenderAndUnSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldNotBeThrown() throws InterruptedException { + Data data = new Data(); + + UnsynchronizedReceiver receiver = new UnsynchronizedReceiver(data); + Thread receiverThread = new Thread(receiver, "receiver-thread"); + receiverThread.start(); + + SynchronizedSender sender = new SynchronizedSender(data); + Thread senderThread = new Thread(sender, "sender-thread"); + senderThread.start(); + + + receiverThread.join(1000); + senderThread.join(1000); + + assertNull(receiver.getMessage()); + assertFalse(sender.hasIllegalMonitorStateExceptionOccurred()); + assertTrue(receiver.hasIllegalMonitorStateExceptionOccurred()); + } + + @Test + void whenUnSyncSenderAndSyncReceiverAreUsed_thenIllegalMonitorExceptionShouldBeThrown() throws InterruptedException { + Data data = new Data(); + + SynchronizedReceiver receiver = new SynchronizedReceiver(data); + Thread receiverThread = new Thread(receiver, "receiver-thread"); + receiverThread.start(); + + UnsynchronizedSender sender = new UnsynchronizedSender(data); + Thread senderThread = new Thread(sender, "sender-thread"); + senderThread.start(); + + + receiverThread.join(1000); + senderThread.join(1000); + + assertNull(receiver.getMessage()); + assertFalse(receiver.hasIllegalMonitorStateExceptionOccurred()); + assertTrue(sender.hasIllegalMonitorStateExceptionOccurred()); + } +} diff --git a/core-java-modules/core-java-io-2/src/main/resources/logback.xml b/core-java-modules/core-java-io-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..f46a64b3cb --- /dev/null +++ b/core-java-modules/core-java-io-2/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java new file mode 100644 index 0000000000..470e06ef96 --- /dev/null +++ b/core-java-modules/core-java-io-3/src/test/java/com/baeldung/tempdirectory/TemporaryDirectoriesUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.tempdirectory; + +import org.apache.commons.io.FileUtils; +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Set; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + + +/** + * Tests several possibilities on how to create + * temporary directories. + * + * @author Rui Vilao (rpvilao@gmail.com) + */ +public class TemporaryDirectoriesUnitTest { + + @Test + public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithPlainJava_thenInsideOSTempDirStructure() throws IOException { + final String tmpdir = Files.createTempDirectory("tmpDirPrefix").toFile().getAbsolutePath(); + final String tmpDirsLocation = System.getProperty("java.io.tmpdir"); + + assertThat(tmpdir).startsWith(tmpDirsLocation); + } + + @Test + public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithGuava_thenInsideOSTempDirStructure() throws IOException { + final String tmpdir = com.google.common.io.Files.createTempDir().getAbsolutePath(); + final String tmpDirsLocation = System.getProperty("java.io.tmpdir"); + + assertThat(tmpdir).startsWith(tmpDirsLocation); + } + + @Test + public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithApacheCommonsIo_thenInsideOSTempDirStructure() throws IOException { + final String tmpDirsLocation = System.getProperty("java.io.tmpdir"); + final Path path = Paths.get(FileUtils.getTempDirectory().getAbsolutePath(), UUID.randomUUID().toString()); + final String tmpdir = Files.createDirectories(path).toFile().getAbsolutePath(); + + assertThat(tmpdir).startsWith(tmpDirsLocation); + } + + @Test + public void givenTempDirWithPrefixWithTargetSpecified_whenCreatePlainJava_thenInsideTarget() throws IOException { + final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix"); + assertThat(tmpdir.toFile().getPath()).startsWith("target"); + } + + @Test + public void givenTempDirWithPrefixWithTargetSpecifiedWithDeleteOnExit_whenCreatePlainJava_thenInsideTarget() throws IOException { + final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix"); + assertThat(tmpdir.toFile().getPath()).startsWith("target"); + tmpdir.toFile().deleteOnExit(); + // we can really assert this test, just as an example. + } + + @Test + public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException { + final FileAttribute> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------")); + + final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs); + assertThat(tmpdir.toFile().getPath()).startsWith("target"); + assertThat(tmpdir.toFile().canWrite()).isFalse(); + } +} diff --git a/core-java-modules/core-java-optional/README.md b/core-java-modules/core-java-optional/README.md index d9d2fe813b..6c83003ea2 100644 --- a/core-java-modules/core-java-optional/README.md +++ b/core-java-modules/core-java-optional/README.md @@ -4,7 +4,6 @@ This module contains articles about Java Optional. ### Relevant Articles: - [Java Optional as Return Type](https://www.baeldung.com/java-optional-return) -- [Guide to Java 8 Optional](https://www.baeldung.com/java-optional) - [Java Optional – orElse() vs orElseGet()](https://www.baeldung.com/java-optional-or-else-vs-or-else-get) - [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional) - [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional) diff --git a/core-kotlin-modules/core-kotlin-collections-2/README.md b/core-kotlin-modules/core-kotlin-collections-2/README.md new file mode 100644 index 0000000000..2dc180b5b3 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/README.md @@ -0,0 +1,7 @@ +## Core Kotlin Collections + +This module contains articles about core Kotlin collections. + +### Relevant articles: + + diff --git a/core-kotlin-modules/core-kotlin-collections-2/pom.xml b/core-kotlin-modules/core-kotlin-collections-2/pom.xml new file mode 100644 index 0000000000..be462eed45 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + core-kotlin-collections-2 + core-kotlin-collections-2 + jar + + + com.baeldung.core-kotlin-modules + core-kotlin-modules + 1.0.0-SNAPSHOT + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.apache.commons + commons-math3 + ${commons-math3.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + + + 1.3.30 + 3.6.1 + 3.10.0 + + + \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt new file mode 100644 index 0000000000..a09e101b59 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/src/main/kotlin/com/baeldung/aggregate/AggregateOperations.kt @@ -0,0 +1,107 @@ +package com.baeldung.aggregate + +class AggregateOperations { + private val numbers = listOf(1, 15, 3, 8) + + fun countList(): Int { + return numbers.count() + } + + fun sumList(): Int { + return numbers.sum() + } + + fun averageList(): Double { + return numbers.average() + } + + fun maximumInList(): Int? { + return numbers.max() + } + + fun minimumInList(): Int? { + return numbers.min() + } + + fun maximumByList(): Int? { + return numbers.maxBy { it % 5 } + } + + fun minimumByList(): Int? { + return numbers.minBy { it % 5 } + } + + fun maximumWithList(): String? { + val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") + return strings.maxWith(compareBy { it.length % 4 }) + } + + fun minimumWithList(): String? { + val strings = listOf("Berlin", "Kolkata", "Prague", "Barcelona") + return strings.minWith(compareBy { it.length % 4 }) + } + + fun sumByList(): Int { + return numbers.sumBy { it * 5 } + } + + fun sumByDoubleList(): Double { + return numbers.sumByDouble { it.toDouble() / 8 } + } + + fun foldList(): Int { + return numbers.fold(100) { total, it -> + println("total = $total, it = $it") + total - it + } // ((((100 - 1)-15)-3)-8) = 73 + } + + fun foldRightList(): Int { + return numbers.foldRight(100) { it, total -> + println("total = $total, it = $it") + total - it + } // ((((100-8)-3)-15)-1) = 73 + } + + fun foldIndexedList(): Int { + return numbers.foldIndexed(100) { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((100 - 3)-8) = 89 + } + + fun foldRightIndexedList(): Int { + return numbers.foldRightIndexed(100) { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((100 - 8)-3) = 89 + } + + fun reduceList(): Int { + return numbers.reduce { total, it -> + println("total = $total, it = $it") + total - it + } // (((1 - 15)-3)-8) = -25 + } + + fun reduceRightList(): Int { + return numbers.reduceRight() { it, total -> + println("total = $total, it = $it") + total - it + } // ((8-3)-15)-1) = -11 + } + + fun reduceIndexedList(): Int { + return numbers.reduceIndexed { index, total, it -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((1-3)-8) = -10 + } + + fun reduceRightIndexedList(): Int { + return numbers.reduceRightIndexed { index, it, total -> + println("total = $total, it = $it, index = $index") + if (index.minus(2) >= 0) total - it else total + } // ((8-3) = 5 + } +} diff --git a/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt new file mode 100644 index 0000000000..a619759b0a --- /dev/null +++ b/core-kotlin-modules/core-kotlin-collections-2/src/test/kotlin/com/baeldung/aggregate/AggregateOperationsUnitTest.kt @@ -0,0 +1,104 @@ +package com.baeldung.aggregate + +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals + +class AggregateOperationsUnitTest { + + private val classUnderTest: AggregateOperations = AggregateOperations() + + @Test + fun whenCountOfList_thenReturnsValue() { + assertEquals(4, classUnderTest.countList()) + } + + @Test + fun whenSumOfList_thenReturnsTotalValue() { + assertEquals(27, classUnderTest.sumList()) + } + + @Test + fun whenAverageOfList_thenReturnsValue() { + assertEquals(6.75, classUnderTest.averageList()) + } + + @Test + fun whenMaximumOfList_thenReturnsMaximumValue() { + assertEquals(15, classUnderTest.maximumInList()) + } + + @Test + fun whenMinimumOfList_thenReturnsMinimumValue() { + assertEquals(1, classUnderTest.minimumInList()) + } + + @Test + fun whenMaxByList_thenReturnsLargestValue() { + assertEquals(3, classUnderTest.maximumByList()) + } + + @Test + fun whenMinByList_thenReturnsSmallestValue() { + assertEquals(15, classUnderTest.minimumByList()) + } + + @Test + fun whenMaxWithList_thenReturnsLargestValue(){ + assertEquals("Kolkata", classUnderTest.maximumWithList()) + } + + @Test + fun whenMinWithList_thenReturnsSmallestValue(){ + assertEquals("Barcelona", classUnderTest.minimumWithList()) + } + + @Test + fun whenSumByList_thenReturnsIntegerValue(){ + assertEquals(135, classUnderTest.sumByList()) + } + + @Test + fun whenSumByDoubleList_thenReturnsDoubleValue(){ + assertEquals(3.375, classUnderTest.sumByDoubleList()) + } + + @Test + fun whenFoldList_thenReturnsValue(){ + assertEquals(73, classUnderTest.foldList()) + } + + @Test + fun whenFoldRightList_thenReturnsValue(){ + assertEquals(73, classUnderTest.foldRightList()) + } + + @Test + fun whenFoldIndexedList_thenReturnsValue(){ + assertEquals(89, classUnderTest.foldIndexedList()) + } + + @Test + fun whenFoldRightIndexedList_thenReturnsValue(){ + assertEquals(89, classUnderTest.foldRightIndexedList()) + } + + @Test + fun whenReduceList_thenReturnsValue(){ + assertEquals(-25, classUnderTest.reduceList()) + } + + @Test + fun whenReduceRightList_thenReturnsValue(){ + assertEquals(-11, classUnderTest.reduceRightList()) + } + + @Test + fun whenReduceIndexedList_thenReturnsValue(){ + assertEquals(-10, classUnderTest.reduceIndexedList()) + } + + @Test + fun whenReduceRightIndexedList_thenReturnsValue(){ + assertEquals(5, classUnderTest.reduceRightIndexedList()) + } +} \ No newline at end of file diff --git a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt index 3b179642ba..aaa6616ed1 100644 --- a/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt +++ b/core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/inline/Inline.kt @@ -22,6 +22,30 @@ fun main() { numbers.each { println(random * it) } // capturing the random variable } +fun namedFunction(): Int { + return 42 +} + +fun anonymous(): () -> Int { + return fun(): Int { + return 42 + } +} + +inline fun List.eachIndexed(f: (Int, T) -> Unit) { + for (i in indices) { + f(i, this[i]) + } +} + +fun List.indexOf(x: T): Int { + eachIndexed { index, value -> + if (value == x) return index + } + + return -1 +} + /** * Generates a random number. */ diff --git a/core-kotlin-modules/pom.xml b/core-kotlin-modules/pom.xml index 8b626e1c1b..67520a7dee 100644 --- a/core-kotlin-modules/pom.xml +++ b/core-kotlin-modules/pom.xml @@ -21,6 +21,7 @@ core-kotlin-advanced core-kotlin-annotations core-kotlin-collections + core-kotlin-collections-2 core-kotlin-concurrency core-kotlin-date-time core-kotlin-design-patterns diff --git a/drools/README.MD b/drools/README.MD index 414ad2dea3..6011c8293c 100644 --- a/drools/README.MD +++ b/drools/README.MD @@ -6,3 +6,4 @@ This module contains articles about Drools - [Introduction to Drools](https://www.baeldung.com/drools) - [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining) +- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) diff --git a/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java b/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java index 551661810d..80e7b93b0c 100644 --- a/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java +++ b/java-collections-conversions-2/src/test/java/com/baeldung/arrayconversion/ArrayToListConversionUnitTest.java @@ -1,21 +1,24 @@ package com.baeldung.arrayconversion; +import org.hamcrest.CoreMatchers; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertArrayEquals; + public class ArrayToListConversionUnitTest { @Test(expected = UnsupportedOperationException.class) public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() { String[] stringArray = new String[] { "A", "B", "C", "D" }; List stringList = Arrays.asList(stringArray); - System.out.println(stringList); stringList.set(0, "E"); - System.out.println(stringList); - System.out.println(Arrays.toString(stringArray)); + assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D")); + assertArrayEquals(stringArray, new String[] { "E", "B", "C", "D" }); stringList.add("F"); } @@ -23,10 +26,10 @@ public class ArrayToListConversionUnitTest { public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() { String[] stringArray = new String[] { "A", "B", "C", "D" }; List stringList = new ArrayList<>(Arrays.asList(stringArray)); - System.out.println(stringList); stringList.set(0, "E"); - System.out.println(stringList); - System.out.println(Arrays.toString(stringArray)); + assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D")); + assertArrayEquals(stringArray, new String[] { "A", "B", "C", "D" }); stringList.add("F"); + assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D", "F")); } } diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index c965fd962d..dbc46bbb97 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -237,6 +237,26 @@ spring-boot:run + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + + set-system-properties + + + + + org.slf4j.simpleLogger.log.com.github.eirslett + error + + + + + + org.apache.maven.plugins maven-compiler-plugin diff --git a/jhipster/pom.xml b/jhipster/pom.xml index dd16205706..1703e82e0e 100644 --- a/jhipster/pom.xml +++ b/jhipster/pom.xml @@ -9,6 +9,8 @@ pom + parent-boot-1 com.baeldung 0.0.1-SNAPSHOT diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index e02f766141..202b3b8763 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -14,29 +14,24 @@ - org.springframework.boot spring-boot-starter-web - org.springframework.security.oauth spring-security-oauth2 ${spring-boot.version} - org.springframework spring-web - com.github.scribejava scribejava-apis ${scribejava.version} - com.google.crypto.tink tink @@ -72,6 +67,16 @@ jasypt ${jasypt.version} + + com.jcraft + jsch + ${jsch.version} + + + org.apache.sshd + sshd-core + ${apache-mina.version} + @@ -81,6 +86,8 @@ 1.2.2 1.9.2 1.58 + 0.1.55 + 2.5.1 diff --git a/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java new file mode 100644 index 0000000000..8a394640c7 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/ssh/apachesshd/SshdDemo.java @@ -0,0 +1,64 @@ +package com.baeldung.ssh.apachesshd; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.util.EnumSet; +import java.util.concurrent.TimeUnit; + +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.channel.ClientChannel; +import org.apache.sshd.client.channel.ClientChannelEvent; +import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.channel.Channel; + +public class SshdDemo { + + public static void main(String[] args) throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + + listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + } + + public static String listFolderStructure(String username, String password, String host, int port, long defaultTimeoutSeconds, String command) throws Exception { + SshClient client = SshClient.setUpDefaultClient(); + client.start(); + try (ClientSession session = client.connect(username, host, port) + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS) + .getSession()) { + session.addPasswordIdentity(password); + session.auth() + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); + try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); + ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) { + channel.setOut(responseStream); + channel.setErr(errorResponseStream); + try { + channel.open() + .verify(defaultTimeoutSeconds, TimeUnit.SECONDS); + try (OutputStream pipedIn = channel.getInvertedIn()) { + pipedIn.write(command.getBytes()); + pipedIn.flush(); + } + channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds)); + String errorString = new String(errorResponseStream.toByteArray()); + if(!errorString.isEmpty()) { + throw new Exception(errorString); + } + String responseString = new String(responseStream.toByteArray()); + return responseString; + } finally { + channel.close(false); + } + } + } finally { + client.stop(); + } + } + +} diff --git a/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java new file mode 100644 index 0000000000..8a6567bfee --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/ssh/jsch/JschDemo.java @@ -0,0 +1,54 @@ +package com.baeldung.ssh.jsch; + +import java.io.ByteArrayOutputStream; + +import com.jcraft.jsch.ChannelExec; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.Session; + +public class JschDemo { + + public static void main(String args[]) throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + listFolderStructure(username, password, host, port, command); + } + + public static String listFolderStructure(String username, String password, String host, int port, String command) throws Exception { + Session session = null; + ChannelExec channel = null; + String response = null; + try { + session = new JSch().getSession(username, host, port); + session.setPassword(password); + session.setConfig("StrictHostKeyChecking", "no"); + session.connect(); + channel = (ChannelExec) session.openChannel("exec"); + channel.setCommand(command); + ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); + ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream(); + channel.setOutputStream(responseStream); + channel.setErrStream(errorResponseStream); + channel.connect(); + while (channel.isConnected()) { + Thread.sleep(100); + } + String errorResponse = new String(errorResponseStream.toByteArray()); + response = new String(responseStream.toByteArray()); + if(!errorResponse.isEmpty()) { + throw new Exception(errorResponse); + } + } finally { + if (session != null) { + session.disconnect(); + } + if (channel != null) { + channel.disconnect(); + } + } + return response; + } +} diff --git a/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java b/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java new file mode 100644 index 0000000000..3cefca05cb --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/ssh/ApacheMinaSshdLiveTest.java @@ -0,0 +1,38 @@ +package com.baeldung.ssh; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.ssh.apachesshd.SshdDemo; + +public class ApacheMinaSshdLiveTest { + + @Test + public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + + assertNotNull(responseString); + } + + @Test(expected = Exception.class) + public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { + String username = "invalidUsername"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + long defaultTimeoutSeconds = 10l; + String command = "ls\n"; + String responseString = SshdDemo.listFolderStructure(username, password, host, port, defaultTimeoutSeconds, command); + + assertNull(responseString); + } + +} diff --git a/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java b/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java new file mode 100644 index 0000000000..c95c3c319c --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/ssh/JSchLiveTest.java @@ -0,0 +1,35 @@ +package com.baeldung.ssh; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.baeldung.ssh.jsch.JschDemo; + +public class JSchLiveTest { + + @Test + public void givenValidCredentials_whenConnectionIsEstablished_thenServerReturnsResponse() throws Exception { + String username = "demo"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + String responseString = JschDemo.listFolderStructure(username, password, host, port, command); + + assertNotNull(responseString); + } + + @Test(expected = Exception.class) + public void givenInvalidCredentials_whenConnectionAttemptIsMade_thenServerReturnsErrorResponse() throws Exception { + String username = "invalidUsername"; + String password = "password"; + String host = "test.rebex.net"; + int port = 22; + String command = "ls"; + String responseString = JschDemo.listFolderStructure(username, password, host, port, command); + + assertNull(responseString); + } +} diff --git a/logging-modules/log-mdc/README.md b/logging-modules/log-mdc/README.md index 0d516619ef..f35bc7fccc 100644 --- a/logging-modules/log-mdc/README.md +++ b/logging-modules/log-mdc/README.md @@ -1,8 +1,6 @@ ### Relevant Articles: -- TBD - [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback) - [Java Logging with Nested Diagnostic Context (NDC)](https://www.baeldung.com/java-logging-ndc-log4j) -- [Drools Using Rules from Excel Files](https://www.baeldung.com/drools-excel) ### References diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java similarity index 99% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java index ad6a064c98..51b27ef5f4 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/BatchProcessing.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.sql.*; import java.util.UUID; diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java similarity index 97% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java index 27aef8b82f..99e5a1ad4a 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import java.util.Objects; diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java similarity index 96% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java index 5ce196ee47..bbcbb5871e 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthor.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthor.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.joins; +package com.baeldung.spring.jdbc.joins; class ArticleWithAuthor { diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java similarity index 98% rename from persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java rename to persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java index 55f03d99ec..48961b786f 100644 --- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAO.java +++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.joins; +package com.baeldung.spring.jdbc.joins; import java.sql.Connection; import java.sql.ResultSet; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java similarity index 98% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java index c905482f55..3cb5e779f5 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/BatchProcessingLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import org.junit.Before; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java similarity index 98% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java index 387c050285..937cf1b833 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcDriverLoadingUnitTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcDriverLoadingUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import static org.junit.Assert.*; 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/spring/jdbc/JdbcLiveTest.java similarity index 99% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java index 81179aade9..c13f94f12a 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/spring/jdbc/JdbcLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import org.apache.log4j.Logger; import org.junit.After; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java similarity index 99% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java index 4e10f8bd43..853e78a68d 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/ResultSetLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc; import static org.junit.Assert.assertEquals; diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java similarity index 99% rename from persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java rename to persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java index 3f69a0e333..055c7ed9ed 100644 --- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbc/joins/ArticleWithAuthorDAOLiveTest.java +++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/joins/ArticleWithAuthorDAOLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.joins; +package com.baeldung.spring.jdbc.joins; import org.junit.After; import org.junit.Before; diff --git a/persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql b/persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql new file mode 100644 index 0000000000..105da7a0c0 --- /dev/null +++ b/persistence-modules/flyway/src/main/resources/db/undo/V1_0__create_book_table.sql @@ -0,0 +1,6 @@ +create table book ( + id numeric, + title varchar(128), + author varchar(256), + constraint pk_book primary key (id) +); \ No newline at end of file diff --git a/persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql b/persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql new file mode 100644 index 0000000000..cd800b00b7 --- /dev/null +++ b/persistence-modules/flyway/src/main/resources/db/undo/V2_0__drop_table_book.sql @@ -0,0 +1 @@ +drop table book; \ No newline at end of file diff --git a/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java new file mode 100644 index 0000000000..03004baf60 --- /dev/null +++ b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoMigrationIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.flywayundo; + +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationInfo; +import org.flywaydb.core.api.MigrationState; +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.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.sql.DataSource; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = FlywayUndoTestConfig.class) +@SpringBootTest +public class FlywayUndoMigrationIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void givenMigrationsExist_whenApplyMigrations_migrationsAreSuccessful() { + Flyway flyway = Flyway.configure() + .dataSource(dataSource) + .schemas("undo") + .locations("db/undo") + .load(); + + flyway.migrate(); + + for (MigrationInfo info : flyway.info().all()) { + assertThat(info.getState()).isEqualTo(MigrationState.SUCCESS); + } + } +} diff --git a/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java new file mode 100644 index 0000000000..5f00626179 --- /dev/null +++ b/persistence-modules/flyway/src/test/java/com/baeldung/flywayundo/FlywayUndoTestConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.flywayundo; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; + +import javax.sql.DataSource; + +@Configuration +public class FlywayUndoTestConfig { + + @Bean + public DataSource createDatasource() { + EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder(); + return dbBuilder.setType(EmbeddedDatabaseType.H2) + .setName("DATABASE") + .build(); + } + +} diff --git a/persistence-modules/hibernate-ogm/src/test/resources/logback.xml b/persistence-modules/hibernate-ogm/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/persistence-modules/hibernate-ogm/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties index c22da2496b..4999a0e600 100644 --- a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/hibernate.properties @@ -5,6 +5,6 @@ hibernate.connection.autocommit=true jdbc.password= hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true +hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/persistence-modules/jpa-hibernate-cascade-type/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 522c281386..4e46c9204b 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -68,7 +68,9 @@ spring-data-jpa-enterprise spring-data-jpa-filtering spring-data-jpa-query + spring-data-jpa-query-2 spring-data-jpa-repo + spring-data-jpa-repo-2 spring-data-jdbc @@ -82,9 +84,9 @@ spring-hibernate4 spring-jpa spring-jpa-2 + spring-jdbc spring-persistence-simple - spring-persistence-simple-2 diff --git a/persistence-modules/spring-data-cassandra/pom.xml b/persistence-modules/spring-data-cassandra/pom.xml index 0f0aae4ebf..b44324dc46 100644 --- a/persistence-modules/spring-data-cassandra/pom.xml +++ b/persistence-modules/spring-data-cassandra/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 @@ -30,6 +30,31 @@ + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + org.springframework spring-test diff --git a/persistence-modules/spring-data-jpa-query-2/README.md b/persistence-modules/spring-data-jpa-query-2/README.md index a4d657d4c6..fdb4ce3db7 100644 --- a/persistence-modules/spring-data-jpa-query-2/README.md +++ b/persistence-modules/spring-data-jpa-query-2/README.md @@ -3,7 +3,9 @@ This module contains articles about querying data using Spring Data JPA ### Relevant Articles: +- [Spring Data JPA @Query Annotation](https://www.baeldung.com/spring-data-jpa-query) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) +- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date) - More articles: [[<-- prev]](../spring-data-jpa-query) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index b9e5120543..22cd373c95 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -3,7 +3,7 @@ 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 - spring-data-jpa-query + spring-data-jpa-query-2 spring-data-jpa-query-2 diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java similarity index 89% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java index 1475eccbf0..179dbf2ae7 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/User.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.model; +package com.baeldung.spring.data.jpa.query; import javax.persistence.*; import java.time.LocalDate; @@ -8,7 +8,6 @@ import java.util.Objects; @Entity @Table(name = "users") public class User { - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @@ -28,9 +27,6 @@ public class User { private Integer status; - @OneToMany - List possessionList; - public User() { super(); } @@ -87,12 +83,20 @@ public class User { return creationDate; } - public List getPossessionList() { - return possessionList; + public LocalDate getLastLoginDate() { + return lastLoginDate; } - public void setPossessionList(List possessionList) { - this.possessionList = possessionList; + public void setLastLoginDate(LocalDate lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; } @Override @@ -119,21 +123,4 @@ public class User { 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-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java similarity index 65% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java index a8e3a536c3..6547e0ef66 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepository.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java @@ -1,6 +1,5 @@ -package com.baeldung.spring.data.persistence.repository; +package com.baeldung.spring.data.jpa.query; -import com.baeldung.spring.data.persistence.model.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -9,51 +8,16 @@ import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -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); @@ -63,6 +27,27 @@ public interface UserRepository extends JpaRepository, UserReposi @Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) Page findAllUsersWithPaginationNative(Pageable pageable); + @Query("SELECT u FROM User u WHERE u.status = ?1") + User findUserByStatus(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2") + User findUserByStatusAndName(Integer status, String name); + + @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 = :status and u.name = :name") + User findUserByStatusAndNameNamedParams(@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(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(value = "SELECT u FROM User u WHERE u.name IN :names") + List findUserByNameList(@Param("names") Collection names); + @Modifying @Query("update User u set u.status = :status where u.name = :name") int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name); @@ -74,25 +59,4 @@ public interface UserRepository extends JpaRepository, UserReposi @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-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java similarity index 72% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java index 77e661bbbe..a3e53528f7 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustom.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java @@ -1,6 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.model.User; +package com.baeldung.spring.data.jpa.query; import java.util.Collection; import java.util.List; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java similarity index 93% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java index 366b2c54d0..033f61fdd3 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCustomImpl.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java @@ -1,6 +1,4 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.model.User; +package com.baeldung.spring.data.jpa.query; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @@ -13,7 +11,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; public class UserRepositoryCustomImpl implements UserRepositoryCustom { - @PersistenceContext private EntityManager entityManager; @@ -48,5 +45,4 @@ public class UserRepositoryCustomImpl implements UserRepositoryCustom { return allUsersStream.collect(Collectors.toList()); } - } diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java similarity index 55% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java index 7fee55be8a..81e5a2f790 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Application.java @@ -1,12 +1,13 @@ -package com.baeldung.spring.transactional; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -class TransactionalCompareApplication { - - public static void main(String[] args) { - SpringApplication.run(TransactionalCompareApplication.class, args); - } -} +package com.baeldung.spring.data.jpa.query.datetime; + +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/boot/domain/Article.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Article.java similarity index 88% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Article.java index de4dbed1a0..bb0e4e88df 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/domain/Article.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/Article.java @@ -1,4 +1,4 @@ -package com.baeldung.boot.domain; +package com.baeldung.spring.data.jpa.query.datetime; import javax.persistence.*; import java.util.Date; 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-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepository.java similarity index 90% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepository.java index 73397ad42e..9ec14884f4 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/daos/ArticleRepository.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepository.java @@ -1,11 +1,9 @@ -package com.baeldung.boot.daos; +package com.baeldung.spring.data.jpa.query.datetime; 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; diff --git a/persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql b/persistence-modules/spring-data-jpa-query-2/src/main/resources/import_entities.sql similarity index 100% rename from persistence-modules/spring-data-jpa-query/src/main/resources/import_entities.sql rename to persistence-modules/spring-data-jpa-query-2/src/main/resources/import_entities.sql 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-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java similarity index 96% rename from persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java index 20fc3cbeaf..38fd804195 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/boot/daos/ArticleRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/datetime/ArticleRepositoryIntegrationTest.java @@ -1,11 +1,4 @@ -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; +package com.baeldung.spring.data.jpa.query.datetime; import org.junit.Test; import org.junit.runner.RunWith; @@ -13,7 +6,12 @@ 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; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql") diff --git a/persistence-modules/spring-data-jpa-query/README.md b/persistence-modules/spring-data-jpa-query/README.md index 34e397394b..27443c2026 100644 --- a/persistence-modules/spring-data-jpa-query/README.md +++ b/persistence-modules/spring-data-jpa-query/README.md @@ -3,7 +3,6 @@ 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) diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md new file mode 100644 index 0000000000..de5188c1ad --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -0,0 +1,5 @@ +## Spring Data JPA - Repositories + +### Relevant Articles: +- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- More articles: [[<-- prev]](/spring-data-jpa-repo/) \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/pom.xml b/persistence-modules/spring-data-jpa-repo-2/pom.xml new file mode 100644 index 0000000000..855b441074 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + spring-data-jpa-repo-2 + spring-data-jpa-repo-2 + + + + + javax.persistence + javax.persistence-api + + + org.springframework.data + spring-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + + + + + com.google.guava + guava + ${guava.version} + + + + + 29.0-jre + + \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java similarity index 85% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java index 64bfe203d0..6833c4c556 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Foo.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/Foo.java @@ -1,16 +1,10 @@ -package com.baeldung.spring.data.persistence.model; +package com.baeldung.spring.data.persistence.repository; +import javax.persistence.*; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; - @Entity public class Foo implements Serializable { - @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @@ -28,8 +22,6 @@ public class Foo implements Serializable { this.name = name; } - // API - public long getId() { return id; } @@ -46,8 +38,6 @@ public class Foo implements Serializable { this.name = name; } - // - @Override public int hashCode() { final int prime = 31; @@ -79,5 +69,4 @@ public class Foo implements Serializable { builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } - -} +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java new file mode 100644 index 0000000000..cb09a92b82 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/FooService.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.data.persistence.repository; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FooService implements IFooService { + @Autowired + private IFooDAO dao; + + @Override + public Foo create(Foo foo) { + return dao.save(foo); + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java similarity index 75% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java index 0b750e37e1..20a81e7bfa 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDao.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooDAO.java @@ -1,13 +1,13 @@ package com.baeldung.spring.data.persistence.repository; -import com.baeldung.spring.data.persistence.model.Foo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface IFooDao extends JpaRepository { +public interface IFooDAO extends JpaRepository { + + Foo findByName(String name); @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-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java new file mode 100644 index 0000000000..8ce6a2d1ae --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/IFooService.java @@ -0,0 +1,5 @@ +package com.baeldung.spring.data.persistence.repository; + +public interface IFooService { + Foo create(Foo foo); +} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java similarity index 90% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java rename to persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java index 604923d615..f73ea94658 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/config/PersistenceConfig.java +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/repository/PersistenceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.persistence.config; +package com.baeldung.spring.data.persistence.repository; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; @@ -20,11 +20,11 @@ import javax.sql.DataSource; import java.util.Properties; @Configuration +@PropertySource("classpath:persistence.properties") +@ComponentScan("com.baeldung.spring.data.persistence.repository") +//@ImportResource("classpath*:*springDataConfig.xml") @EnableTransactionManagement -@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" }) -@ComponentScan({ "com.baeldung.spring.data.persistence" }) -//@ImportResource("classpath*:*springDataJpaRepositoriesConfig.xml") -@EnableJpaRepositories("com.baeldung.spring.data.persistence.repository") +@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository") public class PersistenceConfig { @Autowired @@ -38,7 +38,7 @@ public class PersistenceConfig { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan("com.baeldung.spring.data.persistence.model"); + em.setPackagesToScan("com.baeldung.spring.data.persistence.repository"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); @@ -78,5 +78,4 @@ public class PersistenceConfig { return hibernateProperties; } - -} \ No newline at end of file +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties new file mode 100644 index 0000000000..cb1eab9443 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password=sa \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties new file mode 100644 index 0000000000..339859a6e8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/persistence.properties @@ -0,0 +1,9 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass= + +# hibernate.X +hibernate.hbm2ddl.auto=create-drop +hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml similarity index 82% rename from persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml rename to persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml index 91778a17af..b2616d9eae 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/springDataJpaRepositoriesConfig.xml +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/springDataConfig.xml @@ -2,12 +2,10 @@ - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java new file mode 100644 index 0000000000..141844fa11 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/repository/FooServiceIntegrationTest.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.data.persistence.repository; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = PersistenceConfig.class) +public class FooServiceIntegrationTest { + + @Autowired + private IFooService service; + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 284a7ac2b5..1a95340a97 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -11,6 +11,7 @@ This module contains articles about repositories in Spring Data JPA - [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) +- More articles: [[--> next]](/spring-data-jpa-repo-2/) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index fb80ba33ac..60e59f5186 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -18,12 +18,11 @@ spring-data-mongodb ${org.springframework.data.version} - + - org.springframework.data - spring-data-releasetrain - ${spring-releasetrain} - pom + org.mongodb + mongodb-driver-sync + ${mongodb-driver.version} @@ -66,6 +65,12 @@ com.querydsl querydsl-mongodb ${querydsl.version} + + + org.mongodb + mongo-java-driver + + com.querydsl @@ -96,12 +101,12 @@ - 2.1.9.RELEASE - 4.1.4 + 3.0.3.RELEASE + 4.3.1 1.1.3 - 1.9.2 + 4.1.0 3.2.0.RELEASE - Lovelace-SR9 + 4.0.5 diff --git a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java index 9fa90acf86..8036bbbca2 100644 --- a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/MongoConfig.java @@ -1,16 +1,18 @@ package com.baeldung.config; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; -import converter.ZonedDateTimeReadConverter; -import converter.ZonedDateTimeWriteConverter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; -import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.data.mongodb.MongoTransactionManager; -import org.springframework.data.mongodb.config.AbstractMongoConfiguration; +import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; +import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @@ -18,14 +20,23 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie import com.baeldung.converter.UserWriterConverter; import com.baeldung.event.CascadeSaveMongoEventListener; import com.baeldung.event.UserCascadeSaveMongoEventListener; -import com.mongodb.MongoClient; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; + +import converter.ZonedDateTimeReadConverter; +import converter.ZonedDateTimeWriteConverter; @Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") -public class MongoConfig extends AbstractMongoConfiguration { +public class MongoConfig extends AbstractMongoClientConfiguration { private final List> converters = new ArrayList>(); + @Autowired + private MappingMongoConverter mongoConverter; + @Override protected String getDatabaseName() { return "test"; @@ -33,12 +44,16 @@ public class MongoConfig extends AbstractMongoConfiguration { @Override public MongoClient mongoClient() { - return new MongoClient("127.0.0.1", 27017); + final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); + final MongoClientSettings mongoClientSettings = MongoClientSettings.builder() + .applyConnectionString(connectionString) + .build(); + return MongoClients.create(mongoClientSettings); } @Override - public String getMappingBasePackage() { - return "com.baeldung"; + public Collection getMappingBasePackages() { + return Collections.singleton("com.baeldung"); } @Bean @@ -61,12 +76,12 @@ public class MongoConfig extends AbstractMongoConfiguration { @Bean public GridFsTemplate gridFsTemplate() throws Exception { - return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); + return new GridFsTemplate(mongoDbFactory(), mongoConverter); } @Bean - MongoTransactionManager transactionManager(MongoDbFactory dbFactory) { - return new MongoTransactionManager(dbFactory); + MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) { + return new MongoTransactionManager(dbFactory); } } diff --git a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java index c3ddad5a82..ac823c653f 100644 --- a/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/config/SimpleMongoConfig.java @@ -5,7 +5,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import com.mongodb.MongoClient; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; @Configuration @EnableMongoRepositories(basePackages = "com.baeldung.repository") @@ -13,7 +16,9 @@ public class SimpleMongoConfig { @Bean public MongoClient mongo() throws Exception { - return new MongoClient("localhost"); + final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); + final MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build(); + return MongoClients.create(mongoClientSettings); } @Bean diff --git a/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml b/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml index d59ebcef6e..074a203b1a 100644 --- a/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml +++ b/persistence-modules/spring-data-mongodb/src/main/resources/mongoConfig.xml @@ -12,7 +12,7 @@ - + diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java index 1002dc79eb..dfc3205040 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/aggregation/ZipsAggregationLiveTest.java @@ -40,7 +40,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.aggregation.model.StatePopulation; import com.baeldung.config.MongoConfig; -import com.mongodb.MongoClient; +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -61,7 +64,7 @@ public class ZipsAggregationLiveTest { @BeforeClass public static void setupTests() throws Exception { - client = new MongoClient(); + client = mongoClient(); MongoDatabase testDB = client.getDatabase("test"); MongoCollection zipsCollection = testDB.getCollection("zips"); zipsCollection.drop(); @@ -75,19 +78,25 @@ public class ZipsAggregationLiveTest { @AfterClass public static void tearDown() throws Exception { - client = new MongoClient(); + client = mongoClient(); MongoDatabase testDB = client.getDatabase("test"); MongoCollection zipsCollection = testDB.getCollection("zips"); zipsCollection.drop(); client.close(); } + + private static MongoClient mongoClient() throws Exception { + final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test"); + final MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build(); + return MongoClients.create(mongoClientSettings); + } @Test public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() { GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop"); MatchOperation filterStates = match(new Criteria("statePop").gt(10000000)); - SortOperation sortByPopDesc = sort(new Sort(Direction.DESC, "statePop")); + SortOperation sortByPopDesc = sort(Sort.by(Direction.DESC, "statePop")); Aggregation aggregation = newAggregation(groupByStateAndSumPop, filterStates, sortByPopDesc); AggregationResults result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class); @@ -119,7 +128,7 @@ public class ZipsAggregationLiveTest { GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop"); GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop"); - SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop")); + SortOperation sortByAvgPopAsc = sort(Sort.by(Direction.ASC, "avgCityPop")); ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state") .andExpression("avgCityPop").as("statePop"); LimitOperation limitToOnlyFirstDoc = limit(1); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java index d25b9ece4f..1504c2af68 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/gridfs/GridFSLiveTest.java @@ -113,7 +113,7 @@ public class GridFSLiveTest { assertNotNull(gridFSFile.getUploadDate()); // assertNull(gridFSFile.getAliases()); assertNotNull(gridFSFile.getChunkSize()); - assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png")); + //assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png")); assertThat(gridFSFile.getFilename(), is("test.png")); assertThat(gridFSFile.getMetadata().get("user"), is("alex")); } diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java index e5e4a188ec..6172cc6b1d 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/DocumentQueryLiveTest.java @@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @@ -186,7 +187,7 @@ public class DocumentQueryLiveTest { mongoTemplate.insert(user); Query query = new Query(); - query.with(new Sort(Sort.Direction.ASC, "age")); + query.with(Sort.by(Direction.ASC, "age")); List users = mongoTemplate.find(query, User.class); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java index 4f62f0d7a7..3c4c5d2037 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/mongotemplate/MongoTemplateQueryLiveTest.java @@ -137,7 +137,7 @@ public class MongoTemplateQueryLiveTest { mongoTemplate.insert(user); Query query = new Query(); - query.with(new Sort(Sort.Direction.ASC, "age")); + query.with(Sort.by(Direction.ASC, "age")); List users = mongoTemplate.find(query, User.class); assertThat(users.size(), is(3)); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java index dd7215af7e..a2fa567603 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/repository/UserRepositoryLiveTest.java @@ -14,6 +14,7 @@ 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.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; @@ -127,7 +128,7 @@ public class UserRepositoryLiveTest { user.setName("Adam"); mongoOps.insert(user); - final List users = userRepository.findAll(new Sort(Sort.Direction.ASC, "name")); + final List users = userRepository.findAll(Sort.by(Direction.ASC, "name")); assertThat(users.size(), is(2)); assertThat(users.get(0).getName(), is("Adam")); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index 6cd9657006..d92296beab 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -2,7 +2,6 @@ package com.baeldung.transaction; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import java.util.List; @@ -22,7 +21,6 @@ import org.springframework.transaction.annotation.Transactional; import com.baeldung.config.MongoConfig; import com.baeldung.model.User; import com.baeldung.repository.UserRepository; -import com.mongodb.MongoCommandException; /** * diff --git a/persistence-modules/spring-data-solr/pom.xml b/persistence-modules/spring-data-solr/pom.xml index 9d96c75082..5386c4f9e1 100644 --- a/persistence-modules/spring-data-solr/pom.xml +++ b/persistence-modules/spring-data-solr/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 diff --git a/persistence-modules/spring-jdbc/README.md b/persistence-modules/spring-jdbc/README.md new file mode 100644 index 0000000000..58d7bdec43 --- /dev/null +++ b/persistence-modules/spring-jdbc/README.md @@ -0,0 +1,6 @@ +## Spring JDBC + +### Relevant Articles: +- [Spring JDBC Template](https://www.baeldung.com/spring-jdbc-jdbctemplate) +- [Spring JDBC Template Testing](https://www.baeldung.com/spring-jdbctemplate-testing) +- [Spring JDBC Template In Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml new file mode 100644 index 0000000000..4ac5239318 --- /dev/null +++ b/persistence-modules/spring-jdbc/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + spring-jdbc + spring-jdbc + + + + org.springframework.data + spring-data-jdbc + ${spring-data-jdbc.version} + + + org.springframework.boot + spring-boot-starter-jdbc + + + com.h2database + h2 + + + mysql + mysql-connector-java + runtime + + + + + 2.0.3.RELEASE + + \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java similarity index 84% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java index 99f50abf4c..6d36ac709f 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/config/PersistenceConfig.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/config/PersistenceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey.config; +package com.baeldung.spring.jdbc.autogenkey.config; import javax.sql.DataSource; @@ -16,7 +16,7 @@ public class PersistenceConfig { public DataSource dataSource(Environment env) { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) - .addScript("autogenkey-schema.sql") + .addScript("com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql") .build(); } diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java similarity index 92% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java index cf0dbe4681..0f47473bd7 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey.repository; +package com.baeldung.spring.jdbc.autogenkey.repository; import java.sql.PreparedStatement; diff --git a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java similarity index 90% rename from persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java index 022ea29ed6..247fbf28c2 100644 --- a/persistence-modules/spring-jpa/src/main/java/com/baeldung/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey.repository; +package com.baeldung.spring.jdbc.autogenkey.repository; import java.util.HashMap; import java.util.Map; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/CustomSQLErrorCodeTranslator.java similarity index 93% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/CustomSQLErrorCodeTranslator.java index 48ddfb04b1..9beed9f9df 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/CustomSQLErrorCodeTranslator.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/CustomSQLErrorCodeTranslator.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.sql.SQLException; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/Employee.java similarity index 93% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/Employee.java index a43eb265c7..32ca9ad0d3 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc.template.guide; public class Employee { private int id; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java similarity index 99% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java index eef085f386..11ecd84000 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.sql.PreparedStatement; import java.sql.SQLException; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeRowMapper.java similarity index 92% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeRowMapper.java index d09cd45dbc..f4ea5ac7b6 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/EmployeeRowMapper.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeRowMapper.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.sql.ResultSet; import java.sql.SQLException; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/config/SpringJdbcConfig.java similarity index 70% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/config/SpringJdbcConfig.java index ddc24e439f..0e81babd9a 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jdbc/config/SpringJdbcConfig.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/config/SpringJdbcConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.config; +package com.baeldung.spring.jdbc.template.guide.config; import javax.sql.DataSource; @@ -10,12 +10,16 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration -@ComponentScan("com.baeldung.jdbc") +@ComponentScan("com.baeldung.spring.jdbc") public class SpringJdbcConfig { @Bean public DataSource dataSource() { - return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("classpath:jdbc/schema.sql").addScript("classpath:jdbc/test-data.sql").build(); + return new EmbeddedDatabaseBuilder() + .setType(EmbeddedDatabaseType.H2) + .addScript("classpath:com/baeldung/spring/jdbc/template/guide/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/guide/test-data.sql") + .build(); } // @Bean diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java new file mode 100644 index 0000000000..c771033649 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/Employee.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.jdbc.template.inclause; + +public class Employee { + private int id; + + private String firstName; + + private String lastName; + + + public Employee(int id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + +} diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java similarity index 88% rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java index 2ea42381eb..38b4a58355 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java @@ -1,10 +1,4 @@ -package com.baeldung.jdbc; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.sql.DataSource; +package com.baeldung.spring.jdbc.template.inclause; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -12,6 +6,11 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + @Repository public class EmployeeDAO { private JdbcTemplate jdbcTemplate; @@ -22,15 +21,11 @@ public class EmployeeDAO { namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); } - public int getCountOfEmployees() { - return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); - } - public List getEmployeesFromIdListNamed(List ids) { SqlParameterSource parameters = new MapSqlParameterSource("ids", ids); List employees = namedJdbcTemplate.query( - "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", - parameters, + "SELECT * FROM EMPLOYEE WHERE id IN (:ids)", + parameters, (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); return employees; @@ -39,8 +34,8 @@ public class EmployeeDAO { public List getEmployeesFromIdList(List ids) { String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); List employees = jdbcTemplate.query( - String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), - ids.toArray(), + String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), + ids.toArray(), (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); return employees; @@ -56,12 +51,11 @@ public class EmployeeDAO { jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds); List employees = jdbcTemplate.query( - "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", + "SELECT * FROM EMPLOYEE WHERE id IN (SELECT id FROM employee_tmp)", (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); jdbcTemplate.update("DELETE FROM employee_tmp"); return employees; } - } diff --git a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/Employee.java similarity index 93% rename from persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java rename to persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/Employee.java index bd6fe0fb15..80be897827 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/java/com/baeldung/jdbc/Employee.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc.template.testing; public class Employee { private int id; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java new file mode 100644 index 0000000000..64b146fd47 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.jdbc.template.testing; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; + +import javax.sql.DataSource; + +@Repository +public class EmployeeDAO { + private JdbcTemplate jdbcTemplate; + + public void setDataSource(DataSource dataSource) { + jdbcTemplate = new JdbcTemplate(dataSource); + } + + public int getCountOfEmployees() { + return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/main/resources/autogenkey-schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql similarity index 100% rename from persistence-modules/spring-jpa/src/main/resources/autogenkey-schema.sql rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/application.properties b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/application.properties new file mode 100644 index 0000000000..2f09a522ba --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/application.properties @@ -0,0 +1,3 @@ +spring.datasource.url=jdbc:mysql://localhost:3306/springjdbc +spring.datasource.username=guest_user +spring.datasource.password=guest_password \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/schema.sql similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/jdbc/schema.sql rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/schema.sql diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/test-data.sql similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/jdbc/test-data.sql rename to persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/guide/test-data.sql diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql new file mode 100644 index 0000000000..ef4460e267 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255), + ADDRESS varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql new file mode 100644 index 0000000000..b9ef8fec25 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/inclause/test-data.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada'); + +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA'); + +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland'); + +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA'); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql new file mode 100644 index 0000000000..ef4460e267 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/schema.sql @@ -0,0 +1,7 @@ +CREATE TABLE EMPLOYEE +( + ID int NOT NULL PRIMARY KEY, + FIRST_NAME varchar(255), + LAST_NAME varchar(255), + ADDRESS varchar(255) +); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql new file mode 100644 index 0000000000..b9ef8fec25 --- /dev/null +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/template/testing/test-data.sql @@ -0,0 +1,7 @@ +INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada'); + +INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA'); + +INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland'); + +INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA'); \ No newline at end of file diff --git a/persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java similarity index 76% rename from persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java index aa4d061997..86a23ecc3e 100644 --- a/persistence-modules/spring-jpa/src/test/java/com/baeldung/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbc.autogenkey; +package com.baeldung.spring.jdbc.autogenkey; import static org.junit.Assert.assertEquals; @@ -7,16 +7,17 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; -import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; +import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; +import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; @RunWith(SpringRunner.class) public class GetAutoGenKeyByJDBC { @Configuration - @ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey" }) + @ComponentScan(basePackages = {"com.baeldung.spring.jdbc.autogenkey"}) public static class SpringConfig { } @@ -35,7 +36,6 @@ public class GetAutoGenKeyByJDBC { String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); assertEquals(MESSAGE_CONTENT, loadedMessage); - } @Test diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java similarity index 94% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java index 453656098a..c29d5c4534 100644 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/jdbc/EmployeeDAOIntegrationTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java @@ -1,9 +1,11 @@ -package com.baeldung.jdbc; +package com.baeldung.spring.jdbc.template.guide; import java.util.ArrayList; import java.util.List; -import com.baeldung.jdbc.config.SpringJdbcConfig; +import com.baeldung.spring.jdbc.template.guide.Employee; +import com.baeldung.spring.jdbc.template.guide.EmployeeDAO; +import com.baeldung.spring.jdbc.template.guide.config.SpringJdbcConfig; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAOUnitTest.java similarity index 69% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java rename to persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAOUnitTest.java index 369725bafd..d9a858302b 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jdbc/EmployeeDAOUnitTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAOUnitTest.java @@ -1,22 +1,19 @@ -package com.baeldung.jdbc; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import java.util.ArrayList; -import java.util.List; - -import javax.sql.DataSource; +package com.baeldung.spring.jdbc.template.inclause; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; -import org.springframework.test.util.ReflectionTestUtils; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; @RunWith(MockitoJUnitRunner.class) @@ -30,33 +27,9 @@ public class EmployeeDAOUnitTest { public void setup() { dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) .generateUniqueName(true) - .addScript("classpath:jdbc/schema.sql") - .addScript("classpath:jdbc/test-data.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/inclause/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/inclause/test-data.sql") .build(); - - } - - @Test - public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() { - EmployeeDAO employeeDAO = new EmployeeDAO(); - ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); - Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) - .thenReturn(4); - - assertEquals(4, employeeDAO.getCountOfEmployees()); - - Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) - .thenReturn(3); - - assertEquals(3, employeeDAO.getCountOfEmployees()); - } - - @Test - public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() { - EmployeeDAO employeeDAO = new EmployeeDAO(); - employeeDAO.setDataSource(dataSource); - - assertEquals(4, employeeDAO.getCountOfEmployees()); } @Test diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java new file mode 100644 index 0000000000..3609300c2d --- /dev/null +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.jdbc.template.testing; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; +import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; +import org.springframework.test.util.ReflectionTestUtils; + +import javax.sql.DataSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@RunWith(MockitoJUnitRunner.class) +public class EmployeeDAOUnitTest { + @Mock + JdbcTemplate jdbcTemplate; + + DataSource dataSource; + + @Before + public void setup() { + dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) + .generateUniqueName(true) + .addScript("classpath:com/baeldung/spring/jdbc/template/testing/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/testing/test-data.sql") + .build(); + } + + @Test + public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); + Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) + .thenReturn(4); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + + Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) + .thenReturn(3); + + assertEquals(3, employeeDAO.getCountOfEmployees()); + } + + @Test + public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + employeeDAO.setDataSource(dataSource); + + assertEquals(4, employeeDAO.getCountOfEmployees()); + } +} diff --git a/persistence-modules/spring-jpa-2/README.md b/persistence-modules/spring-jpa-2/README.md index b1786f49bd..fe661c2f28 100644 --- a/persistence-modules/spring-jpa-2/README.md +++ b/persistence-modules/spring-jpa-2/README.md @@ -2,4 +2,9 @@ ### Relevant Articles: - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) +- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) +- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring) +- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) +- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) +- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) - More articles: [[<-- prev]](/spring-jpa) \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/pom.xml b/persistence-modules/spring-jpa-2/pom.xml index 08a1f0c6a3..1c21f6b98d 100644 --- a/persistence-modules/spring-jpa-2/pom.xml +++ b/persistence-modules/spring-jpa-2/pom.xml @@ -15,6 +15,17 @@ + + org.springframework.boot + spring-boot-starter + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + org.springframework spring-orm @@ -43,8 +54,25 @@ h2 ${h2.version} + + org.apache.tomcat + tomcat-dbcp + ${tomcat-dbcp.version} + + + + + com.google.guava + guava + ${guava.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot.version} + org.springframework spring-test @@ -57,6 +85,13 @@ 5.1.5.RELEASE + + + 9.0.0.M26 + + + 21.0 + 2.2.6.RELEASE \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/BarHibernateDAO.java diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java similarity index 97% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java index 150e3778af..da23803d76 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateConf.java @@ -51,7 +51,7 @@ public class HibernateConf { return transactionManager; } - private final Properties hibernateProperties() { + private Properties hibernateProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/HibernateXMLConf.java diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/hibernate/bootstrap/model/TestEntity.java diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java similarity index 87% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java index e406f896dc..bd78fe647d 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractHibernateDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractHibernateDao.java @@ -1,52 +1,49 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; -import java.util.List; +package com.baeldung.spring.dao.generics; +import com.google.common.base.Preconditions; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; -import com.google.common.base.Preconditions; +import java.io.Serializable; +import java.util.List; @SuppressWarnings("unchecked") -public abstract class AbstractHibernateDao extends AbstractDao implements IOperations { +public abstract class AbstractHibernateDao { + private Class clazz; @Autowired protected SessionFactory sessionFactory; - // API + public void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } - @Override + // API public T findOne(final long id) { return (T) getCurrentSession().get(clazz, id); } - @Override public List findAll() { return getCurrentSession().createQuery("from " + clazz.getName()).list(); } - @Override public T create(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().saveOrUpdate(entity); return entity; } - @Override public T update(final T entity) { Preconditions.checkNotNull(entity); return (T) getCurrentSession().merge(entity); } - @Override public void delete(final T entity) { Preconditions.checkNotNull(entity); getCurrentSession().delete(entity); } - @Override public void deleteById(final long entityId) { final T entity = findOne(entityId); Preconditions.checkState(entity != null); @@ -56,5 +53,4 @@ public abstract class AbstractHibernateDao extends Abstr protected Session getCurrentSession() { return sessionFactory.getCurrentSession(); } - } \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java similarity index 96% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java index a6542c5cb1..e68a9281a0 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/AbstractJpaDAO.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/AbstractJpaDAO.java @@ -1,4 +1,4 @@ -package com.baeldung.jpa.dao; +package com.baeldung.spring.dao.generics; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @@ -6,7 +6,6 @@ import java.io.Serializable; import java.util.List; public abstract class AbstractJpaDAO { - private Class clazz; @PersistenceContext(unitName = "entityManagerFactory") @@ -42,5 +41,4 @@ public abstract class AbstractJpaDAO { final T entity = findOne(entityId); delete(entity); } - } \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java similarity index 73% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java index 009876f8cb..33284d9b8e 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Foo.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/Foo.java @@ -1,21 +1,10 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; - -import javax.persistence.Cacheable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedNativeQueries; -import javax.persistence.NamedNativeQuery; +package com.baeldung.spring.dao.generics; import org.hibernate.annotations.CacheConcurrencyStrategy; +import javax.persistence.*; +import java.io.Serializable; + @Entity @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @@ -41,18 +30,6 @@ public class Foo implements Serializable { @Column(name = "NAME") private String name; - @ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER) - @JoinColumn(name = "BAR_ID") - private Bar bar; - - public Bar getBar() { - return bar; - } - - public void setBar(final Bar bar) { - this.bar = bar; - } - public Long getId() { return id; } @@ -100,5 +77,4 @@ public class Foo implements Serializable { builder.append("Foo [name=").append(name).append("]"); return builder.toString(); } - } diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java new file mode 100644 index 0000000000..4c2014c717 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/FooService.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.dao.generics; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class FooService implements IFooService { + + IGenericDao dao; + + @Autowired + public void setDao(IGenericDao daoToSet) { + dao = daoToSet; + dao.setClazz(Foo.class); + } + + @Override + public Foo retrieveByName(String name) { + return null; + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java similarity index 89% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java index 18b16fa033..619a144176 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericHibernateDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericHibernateDao.java @@ -1,11 +1,11 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; +package com.baeldung.spring.dao.generics; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; +import java.io.Serializable; + @Repository @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class GenericHibernateDao extends AbstractHibernateDao implements IGenericDao { diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java similarity index 80% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java index d4da194f4d..cf89b05f96 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/GenericJpaDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/GenericJpaDao.java @@ -1,12 +1,10 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; +package com.baeldung.spring.dao.generics; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Repository; -import com.baeldung.jpa.dao.AbstractJpaDAO; +import java.io.Serializable; @Repository @Scope(BeanDefinition.SCOPE_PROTOTYPE) diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java new file mode 100644 index 0000000000..2d525de405 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IFooService.java @@ -0,0 +1,5 @@ +package com.baeldung.spring.dao.generics; + +public interface IFooService { + Foo retrieveByName(String name); +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java similarity index 64% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java index 34c5e0f616..3fd7baf63f 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IOperations.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/dao/generics/IGenericDao.java @@ -1,9 +1,10 @@ -package com.baeldung.persistence.dao.common; +package com.baeldung.spring.dao.generics; import java.io.Serializable; import java.util.List; -public interface IOperations { +public interface IGenericDao { + void setClazz(Class< T > clazzToSet); T findOne(final long id); @@ -16,5 +17,4 @@ public interface IOperations { void delete(final T entity); void deleteById(final long entityId); - } diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java new file mode 100644 index 0000000000..c0a99e92c8 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/AbstractHibernateDao.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.hibernate; + +import com.google.common.base.Preconditions; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import java.io.Serializable; +import java.util.List; + +@SuppressWarnings("unchecked") +public abstract class AbstractHibernateDao { + private Class clazz; + + @Autowired + protected SessionFactory sessionFactory; + + protected final void setClazz(final Class clazzToSet) { + clazz = Preconditions.checkNotNull(clazzToSet); + } + + // API + public T findOne(final long id) { + return (T) getCurrentSession().get(clazz, id); + } + + public List findAll() { + return getCurrentSession().createQuery("from " + clazz.getName()).list(); + } + + public T create(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().saveOrUpdate(entity); + return entity; + } + + public T update(final T entity) { + Preconditions.checkNotNull(entity); + return (T) getCurrentSession().merge(entity); + } + + public void delete(final T entity) { + Preconditions.checkNotNull(entity); + getCurrentSession().delete(entity); + } + + public void deleteById(final long entityId) { + final T entity = findOne(entityId); + Preconditions.checkState(entity != null); + delete(entity); + } + + protected Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java new file mode 100644 index 0000000000..f92b510071 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/Foo.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.hibernate; + +import javax.persistence.*; +import java.io.Serializable; + +@Entity +public class Foo implements Serializable { + private static final long serialVersionUID = 1L; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "ID") + private Long id; + @Column(name = "NAME") + private String name; + + 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; + } +} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java similarity index 55% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java index 67c10fe7fe..d5495d4eb1 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/hibernate/dao/FooDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/FooDao.java @@ -1,14 +1,9 @@ -package com.baeldung.hibernate.dao; +package com.baeldung.spring.hibernate; -import com.baeldung.persistence.model.Foo; import org.springframework.stereotype.Repository; -import com.baeldung.jpa.dao.IFooDao; -import com.baeldung.persistence.dao.common.AbstractHibernateDao; - @Repository public class FooDao extends AbstractHibernateDao implements IFooDao { - public FooDao() { super(); @@ -16,5 +11,4 @@ public class FooDao extends AbstractHibernateDao implements IFooDao { } // API - } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java similarity index 65% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java index 8140c56edd..d397163be5 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/IFooDao.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/hibernate/IFooDao.java @@ -1,21 +1,15 @@ -package com.baeldung.jpa.dao; +package com.baeldung.spring.hibernate; import java.util.List; -import com.baeldung.persistence.model.Foo; - public interface IFooDao { - Foo findOne(long id); List findAll(); - Foo create(Foo entity); - Foo update(Foo entity); void delete(Foo entity); void deleteById(long entityId); - } diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java similarity index 91% rename from persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java rename to persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java index e8a2aefd6b..497d735c10 100644 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceJPAConfig.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/jpa/guide/PersistenceJPAConfig.java @@ -1,9 +1,8 @@ -package com.baeldung.config; +package com.baeldung.spring.jpa.guide; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; @@ -21,17 +20,12 @@ import java.util.Properties; @Configuration @EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) +@PropertySource("classpath:persistence-h2.properties") public class PersistenceJPAConfig { @Autowired private Environment env; - public PersistenceJPAConfig() { - super(); - } - // beans @Bean @@ -75,9 +69,7 @@ public class PersistenceJPAConfig { hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false"); - - + return hibernateProperties; } - } \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java new file mode 100644 index 0000000000..407d8e3394 --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/spring/transaction/FooService.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.transaction; + +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +public class FooService {} \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/src/main/resources/application.properties b/persistence-modules/spring-jpa-2/src/main/resources/application.properties new file mode 100644 index 0000000000..0270c1683e --- /dev/null +++ b/persistence-modules/spring-jpa-2/src/main/resources/application.properties @@ -0,0 +1,11 @@ +# H2 +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 + +# MySQL +#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +#spring.datasource.username=mysqluser +#spring.datasource.password=mysqlpass +#spring.datasource.url=jdbc:mysql://localhost:3306/myDb?createDatabaseIfNotExist=true diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml b/persistence-modules/spring-jpa-2/src/main/resources/hibernate5Configuration.xml similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Configuration.xml rename to persistence-modules/spring-jpa-2/src/main/resources/hibernate5Configuration.xml diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence-h2.properties rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-h2.properties diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml b/persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml similarity index 89% rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml index 57687c306d..54774442c6 100644 --- a/persistence-modules/spring-persistence-simple/src/main/resources/persistence.xml +++ b/persistence-modules/spring-jpa-2/src/main/resources/persistence-jpa-config.xml @@ -6,7 +6,6 @@ http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - @@ -14,8 +13,6 @@ - diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties b/persistence-modules/spring-jpa-2/src/main/resources/persistence-mysql.properties similarity index 100% rename from persistence-modules/spring-persistence-simple/src/main/resources/persistence-mysql.properties rename to persistence-modules/spring-jpa-2/src/main/resources/persistence-mysql.properties diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java rename to persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateBootstrapIntegrationTest.java diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java similarity index 100% rename from persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java rename to persistence-modules/spring-jpa-2/src/test/java/com/baeldung/hibernate/bootstrap/HibernateXMLBootstrapIntegrationTest.java diff --git a/persistence-modules/spring-persistence-simple-2/README.md b/persistence-modules/spring-persistence-simple-2/README.md deleted file mode 100644 index d80c7efc57..0000000000 --- a/persistence-modules/spring-persistence-simple-2/README.md +++ /dev/null @@ -1,6 +0,0 @@ -### Relevant Articles: - -- [Spring JdbcTemplate Unit Testing](https://www.baeldung.com/spring-jdbctemplate-testing) -- [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) -- [Transactional Annotations: Spring vs. JTA](https://www.baeldung.com/spring-vs-jta-transactional) -- [Test a Mock JNDI Datasource with Spring](https://www.baeldung.com/spring-mock-jndi-datasource) diff --git a/persistence-modules/spring-persistence-simple-2/pom.xml b/persistence-modules/spring-persistence-simple-2/pom.xml deleted file mode 100644 index b8f3b384a2..0000000000 --- a/persistence-modules/spring-persistence-simple-2/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - 4.0.0 - spring-persistence-simple-2 - 0.1-SNAPSHOT - spring-persistence-simple-2 - - - com.baeldung - persistence-modules - 1.0.0-SNAPSHOT - - - - - - org.springframework - spring-orm - ${org.springframework.version} - - - org.springframework - spring-context - ${org.springframework.version} - - - - - com.h2database - h2 - ${h2.version} - test - - - - - com.github.h-thurow - simple-jndi - ${simple-jndi.version} - - - - - org.springframework - spring-test - ${org.springframework.version} - test - - - org.mockito - mockito-core - ${mockito.version} - test - - - - - - 5.2.4.RELEASE - - 1.4.200 - - 0.23.0 - - 3.3.3 - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql deleted file mode 100644 index be102431ca..0000000000 --- a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/schema.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE EMPLOYEE -( - ID int NOT NULL PRIMARY KEY, - FIRST_NAME varchar(255), - LAST_NAME varchar(255) -); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql b/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql deleted file mode 100644 index 5421c09849..0000000000 --- a/persistence-modules/spring-persistence-simple-2/src/main/resources/jdbc/test-data.sql +++ /dev/null @@ -1,4 +0,0 @@ -INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling'); -INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth'); -INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds'); -INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie'); \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/README.md b/persistence-modules/spring-persistence-simple/README.md index d665433eef..baa9107f4e 100644 --- a/persistence-modules/spring-persistence-simple/README.md +++ b/persistence-modules/spring-persistence-simple/README.md @@ -4,15 +4,9 @@ ### Relevant Articles: -- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa) -- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring) -- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate) -- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics) -- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring) -- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) -- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query) -- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate) - [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation) +- [JTA Transaction with Spring](https://www.baeldung.com/spring-vs-jta-transactional) +- [Mock JNDI Datasource](https://www.baeldung.com/spring-mock-jndi-datasource) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-persistence-simple/pom.xml b/persistence-modules/spring-persistence-simple/pom.xml index 7318ec55bd..a069f70994 100644 --- a/persistence-modules/spring-persistence-simple/pom.xml +++ b/persistence-modules/spring-persistence-simple/pom.xml @@ -24,72 +24,48 @@ spring-context ${org.springframework.version} - - org.springframework - spring-aspects - ${org.springframework.version} - + - org.hibernate - hibernate-core - ${hibernate.version} - - - javax.transaction - jta - ${jta.version} - - - org.hibernate - hibernate-entitymanager - ${hibernate.version} - - - mysql - mysql-connector-java - ${mysql-connector-java.version} - runtime + javax.persistence + javax.persistence-api + ${persistence-api.version} org.springframework.data spring-data-jpa ${spring-data-jpa.version} + + javax.transaction + javax.transaction-api + ${transaction-api.version} + + + org.springframework + spring-tx + ${org.springframework.version} + + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + com.h2database h2 ${h2.version} - - - - org.apache.tomcat - tomcat-dbcp - ${tomcat-dbcp.version} - - - - - - com.google.guava - guava - ${guava.version} - - - org.assertj - assertj-core - ${assertj.version} - - - - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} test + + + com.github.h-thurow + simple-jndi + ${simple-jndi.version} + + + org.springframework spring-test @@ -97,56 +73,25 @@ test - com.querydsl - querydsl-jpa - ${querydsl.version} - - - com.querydsl - querydsl-apt - ${querydsl.version} + org.mockito + mockito-core + ${mockito.version} + test - - - - com.mysema.maven - apt-maven-plugin - ${apt-maven-plugin.version} - - - generate-sources - - process - - - target/generated-sources - com.querydsl.apt.jpa.JPAAnnotationProcessor - - - - - - - - 5.2.6.RELEASE - + 5.2.4.RELEASE + 2.3.3.RELEASE - 5.4.13.Final - 8.0.19 - 1.4.200 + 2.2 + 1.3 2.2.7.RELEASE - 9.0.0.M26 - 1.1 - 4.2.1 - - - 21.0 - 3.8.0 - 1.1.3 + 1.4.200 + + 0.23.0 + + 3.3.3 - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java deleted file mode 100644 index cdddbaa787..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/config/PersistenceConfig.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.baeldung.config; - -import com.baeldung.persistence.service.FooService; -import com.google.common.base.Preconditions; -import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; -import org.springframework.orm.hibernate5.HibernateTransactionManager; -import org.springframework.orm.hibernate5.LocalSessionFactoryBean; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.JpaVendorAdapter; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import javax.sql.DataSource; -import java.util.Properties; - -@Configuration -@EnableTransactionManagement -@EnableJpaAuditing -@PropertySource({ "classpath:persistence-mysql.properties" }) -@ComponentScan(basePackages = { "com.baeldung.persistence.dao", "com.baeldung.jpa.dao" }) -public class PersistenceConfig { - - @Autowired - private Environment env; - - public PersistenceConfig() { - super(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory() { - final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); - sessionFactory.setDataSource(restDataSource()); - sessionFactory.setPackagesToScan("com.baeldung.persistence.model"); - sessionFactory.setHibernateProperties(hibernateProperties()); - - return sessionFactory; - } - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean(); - emf.setDataSource(restDataSource()); - emf.setPackagesToScan("com.baeldung.persistence.model"); - - final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - emf.setJpaVendorAdapter(vendorAdapter); - emf.setJpaProperties(hibernateProperties()); - - return emf; - } - - @Bean - public DataSource restDataSource() { - final BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - @Bean - public PlatformTransactionManager hibernateTransactionManager() { - final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); - transactionManager.setSessionFactory(sessionFactory().getObject()); - return transactionManager; - } - - @Bean - public PlatformTransactionManager jpaTransactionManager() { - final JpaTransactionManager transactionManager = new JpaTransactionManager(); - transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - @Bean - public FooService fooService() { - return new FooService(); - } - - private Properties hibernateProperties() { - 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", "true"); - - // Envers properties - hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); - - return hibernateProperties; - } - -} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java deleted file mode 100644 index e79a44a0c2..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/jpa/dao/FooDao.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.jpa.dao; - -import com.baeldung.persistence.model.Foo; -import org.springframework.stereotype.Repository; - -@Repository -public class FooDao extends AbstractJpaDAO implements IFooDao { - - public FooDao() { - super(); - - setClazz(Foo.class); - } - - // API - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java deleted file mode 100644 index 5a6c76a93a..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/AbstractDao.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; - -import com.google.common.base.Preconditions; - -public abstract class AbstractDao implements IOperations { - - protected Class clazz; - - protected final void setClazz(final Class clazzToSet) { - clazz = Preconditions.checkNotNull(clazzToSet); - } -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java deleted file mode 100644 index 8d8af18394..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/dao/common/IGenericDao.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.baeldung.persistence.dao.common; - -import java.io.Serializable; - -public interface IGenericDao extends IOperations { - // -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java deleted file mode 100644 index 5a88ecc6cf..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/model/Bar.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.baeldung.persistence.model; - -import java.io.Serializable; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; - -@Entity -public class Bar implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private long id; - - @Column(nullable = false) - private String name; - - @OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @OrderBy("name ASC") - List fooList; - - public Bar() { - super(); - } - - public Bar(final String name) { - super(); - - this.name = name; - } - - // API - - 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; - } - - public List getFooList() { - return fooList; - } - - public void setFooList(final List fooList) { - this.fooList = fooList; - } - - // - - @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(); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java deleted file mode 100644 index efe9743670..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/persistence/service/FooService.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.baeldung.persistence.service; - -import java.util.List; - -import com.baeldung.jpa.dao.IFooDao; -import com.baeldung.persistence.model.Foo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@Transactional -public class FooService { - - @Autowired - private IFooDao dao; - - public FooService() { - super(); - } - - // API - - public void create(final Foo entity) { - dao.create(entity); - } - - public Foo findOne(final long id) { - return dao.findOne(id); - } - - public List findAll() { - return dao.findAll(); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java deleted file mode 100644 index 44ca9fc62e..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/model/Possession.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.baeldung.spring.data.persistence.model; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@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-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java deleted file mode 100644 index 00e7ac01e4..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/IFooService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.spring.data.persistence.service; - -import com.baeldung.spring.data.persistence.model.Foo; - -import com.baeldung.persistence.dao.common.IOperations; - -public interface IFooService extends IOperations { - - Foo retrieveByName(String name); - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java deleted file mode 100644 index 61c7d6fcaa..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/common/AbstractService.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.baeldung.spring.data.persistence.service.common; - -import java.io.Serializable; -import java.util.List; - -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.transaction.annotation.Transactional; - -import com.baeldung.persistence.dao.common.IOperations; -import com.google.common.collect.Lists; - -@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()); - } - - // 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(T entity) { - getDao().delete(entity); - } - - @Override - public void deleteById(long entityId) { - T entity = findOne(entityId); - delete(entity); - } - - protected abstract PagingAndSortingRepository getDao(); - -} diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java deleted file mode 100644 index c1406b8602..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/data/persistence/service/impl/FooService.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.baeldung.spring.data.persistence.service.impl; - - -import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.spring.data.persistence.repository.IFooDao; -import com.baeldung.spring.data.persistence.service.IFooService; -import com.baeldung.spring.data.persistence.service.common.AbstractService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.repository.PagingAndSortingRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@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); - } - -} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/Car.java similarity index 95% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/Car.java index 1219111ffa..cb0dc21f7d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/Car.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.transactional.entity; +package com.baeldung.spring.transactional; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarRepository.java similarity index 55% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarRepository.java index f8ecc8f550..ca82954751 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarRepository.java @@ -1,6 +1,5 @@ -package com.baeldung.spring.transactional.repository; +package com.baeldung.spring.transactional; -import com.baeldung.spring.transactional.entity.Car; import org.springframework.data.jpa.repository.JpaRepository; public interface CarRepository extends JpaRepository { diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarService.java similarity index 83% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarService.java index 0821ddb02b..00396d191a 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/CarService.java @@ -1,7 +1,5 @@ -package com.baeldung.spring.transactional.service; +package com.baeldung.spring.transactional; -import com.baeldung.spring.transactional.entity.Car; -import com.baeldung.spring.transactional.repository.CarRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/RentalService.java similarity index 75% rename from persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java rename to persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/RentalService.java index 0aa0815a98..468ac2e53d 100644 --- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java +++ b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/spring/transactional/RentalService.java @@ -1,7 +1,5 @@ -package com.baeldung.spring.transactional.service; +package com.baeldung.spring.transactional; -import com.baeldung.spring.transactional.entity.Car; -import com.baeldung.spring.transactional.repository.CarRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java b/persistence-modules/spring-persistence-simple/src/main/java/com/baeldung/util/IDUtil.java deleted file mode 100644 index 45e72e046d..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/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-persistence-simple-2/src/main/resources/jndi/datasource.properties b/persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties similarity index 100% rename from persistence-modules/spring-persistence-simple-2/src/main/resources/jndi/datasource.properties rename to persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml deleted file mode 100644 index 55546a862a..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/hibernate5Config.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - ${hibernate.hbm2ddl.auto} - ${hibernate.dialect} - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml b/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml deleted file mode 100644 index e3d7452eb1..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/jdbc/springJdbc-config.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple-2/src/main/resources/jndi.properties b/persistence-modules/spring-persistence-simple/src/main/resources/jndi.properties similarity index 69% rename from persistence-modules/spring-persistence-simple-2/src/main/resources/jndi.properties rename to persistence-modules/spring-persistence-simple/src/main/resources/jndi.properties index d976f16c02..4ab5b3ba8b 100644 --- a/persistence-modules/spring-persistence-simple-2/src/main/resources/jndi.properties +++ b/persistence-modules/spring-persistence-simple/src/main/resources/jndi.properties @@ -3,4 +3,4 @@ org.osjava.sj.jndi.shared=true org.osjava.sj.delimiter=. jndi.syntax.separator=/ org.osjava.sj.space=java:/comp/env -org.osjava.sj.root=src/main/resources/jndi +org.osjava.sj.root=src/main/resources/com/baeldung/spring/jndi/datasource/mock diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml b/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml deleted file mode 100644 index ec0dc2469a..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/logback.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - web - %date [%thread] %-5level %logger{36} - %message%n - - - - - - - - - - - - - - \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql b/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql deleted file mode 100644 index 9cedb75c37..0000000000 --- a/persistence-modules/spring-persistence-simple/src/main/resources/stored_procedure.sql +++ /dev/null @@ -1,20 +0,0 @@ -DELIMITER // - CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255)) - LANGUAGE SQL - DETERMINISTIC - SQL SECURITY DEFINER - BEGIN - SELECT * FROM foo WHERE name = fooName; - END // -DELIMITER ; - - -DELIMITER // - CREATE PROCEDURE GetAllFoos() - LANGUAGE SQL - DETERMINISTIC - SQL SECURITY DEFINER - BEGIN - SELECT * FROM foo; - END // -DELIMITER ; \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java deleted file mode 100644 index fbda459d65..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Foo; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -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; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooPaginationPersistenceIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private FooService fooService; - - @Before - public final void before() { - final int minimalNumberOfEntities = 25; - if (fooService.findAll().size() <= minimalNumberOfEntities) { - for (int i = 0; i < minimalNumberOfEntities; i++) { - fooService.create(new Foo(randomAlphabetic(6))); - } - } - } - - // tests - - @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { - // - } - - @SuppressWarnings("unchecked") - @Test - public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() { - final int pageSize = 10; - - final Query query = entityManager.createQuery("From Foo"); - configurePagination(query, 1, pageSize); - - // When - final List fooList = query.getResultList(); - - // Then - assertThat(fooList, hasSize(pageSize)); - } - - @SuppressWarnings("unchecked") - @Test - public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() { - final int pageSize = 10; - final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f"); - final long countResult = (long) queryTotal.getSingleResult(); - - final Query query = entityManager.createQuery("Select f from Foo as f order by f.id"); - final int lastPage = (int) ((countResult / pageSize) + 1); - configurePagination(query, lastPage, pageSize); - final List fooList = query.getResultList(); - - // Then - assertThat(fooList, hasSize(lessThan(pageSize + 1))); - } - - @SuppressWarnings("unchecked") - @Test - public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() { - final int pageSize = 10; - - final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name"); - final List fooIds = queryIds.getResultList(); - - final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids"); - query.setParameter("ids", fooIds.subList(0, pageSize)); - - final List fooList = query.getResultList(); - - // Then - assertThat(fooList, hasSize(pageSize)); - } - - @Test - public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() { - final int pageSize = 10; - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - final TypedQuery typedQuery = entityManager.createQuery(select); - typedQuery.setFirstResult(0); - typedQuery.setMaxResults(pageSize); - final List fooList = typedQuery.getResultList(); - - // Then - assertThat(fooList, hasSize(pageSize)); - } - - @Test - public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() { - int pageNumber = 1; - final int pageSize = 10; - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - - final CriteriaQuery countQuery = criteriaBuilder.createQuery(Long.class); - countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class))); - final Long count = entityManager.createQuery(countQuery).getSingleResult(); - - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - - TypedQuery typedQuery; - while (pageNumber < count.intValue()) { - typedQuery = entityManager.createQuery(select); - typedQuery.setFirstResult(pageNumber - 1); - typedQuery.setMaxResults(pageSize); - System.out.println("Current page: " + typedQuery.getResultList()); - pageNumber += pageSize; - } - - } - - // UTIL - - final int determineLastPage(final int pageSize, final long countResult) { - return (int) (countResult / pageSize) + 1; - } - - final void configurePagination(final Query query, final int pageNumber, final int pageSize) { - query.setFirstResult((pageNumber - 1) * pageSize); - query.setMaxResults(pageSize); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index f4b70a7fde..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Foo; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -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; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooServicePersistenceIntegrationTest { - - @Autowired - private FooService 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(randomAlphabetic(2048))); - } - - @Test(expected = DataIntegrityViolationException.class) - public final void whenEntityWithLongNameIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - @Test(expected = InvalidDataAccessApiUsageException.class) - public final void whenSameEntityIsCreatedTwice_thenDataException() { - final Foo entity = new Foo(randomAlphabetic(8)); - service.create(entity); - service.create(entity); - } - - @Test(expected = DataAccessException.class) - public final void temp_whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo(randomAlphabetic(2048))); - } - - @Test - public final void whenEntityIsCreated_thenFound() { - final Foo fooEntity = new Foo("abc"); - service.create(fooEntity); - final Foo found = service.findOne(fooEntity.getId()); - Assert.assertNotNull(found); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java deleted file mode 100644 index c3db45ab41..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingIntegrationTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.baeldung.persistence.service; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Bar; -import com.baeldung.persistence.model.Foo; -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; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -@SuppressWarnings("unchecked") -public class FooServiceSortingIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - // tests - - @Test - public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() { - final String jql = "Select f from Foo as f order by f.id"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() { - final String jql = "Select f from Foo as f order by f.id desc"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingByTwoAttributes_thenPrintSortedResult() { - final String jql = "Select f from Foo as f order by f.name asc, f.id desc"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingFooByBar_thenBarsSorted() { - final String jql = "Select f from Foo as f order by f.name, f.bar.id"; - final Query barJoinQuery = entityManager.createQuery(jql); - final List fooList = barJoinQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - if (foo.getBar() != null) { - System.out.print("-------BarId:" + foo.getBar().getId()); - } - } - } - - @Test - public final void whenSortinfBar_thenPrintBarsSortedWithFoos() { - final String jql = "Select b from Bar as b order by b.id"; - final Query barQuery = entityManager.createQuery(jql); - final List barList = barQuery.getResultList(); - for (final Bar bar : barList) { - System.out.println("Bar Id:" + bar.getId()); - for (final Foo foo : bar.getFooList()) { - System.out.println("FooName:" + foo.getName()); - } - } - } - - @Test - public final void whenSortingFooWithCriteria_thenPrintSortedFoos() { - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name"))); - final TypedQuery typedQuery = entityManager.createQuery(select); - final List fooList = typedQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId()); - } - } - - @Test - public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() { - final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - final CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Foo.class); - final Root from = criteriaQuery.from(Foo.class); - final CriteriaQuery select = criteriaQuery.select(from); - criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id"))); - final TypedQuery typedQuery = entityManager.createQuery(select); - final List fooList = typedQuery.getResultList(); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId()); - } - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java deleted file mode 100644 index 103321fc64..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNull; - -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; - -import com.baeldung.config.PersistenceJPAConfig; -import com.baeldung.persistence.model.Foo; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -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; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooServiceSortingWitNullsManualIntegrationTest { - - @PersistenceContext - private EntityManager entityManager; - - @Autowired - private FooService service; - - // tests - - @SuppressWarnings("unchecked") - @Test - public final void whenSortingByStringNullLast_thenLastNull() { - service.create(new Foo()); - service.create(new Foo(randomAlphabetic(6))); - - final String jql = "Select f from Foo as f order by f.name desc NULLS LAST"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - assertNull(fooList.get(fooList.toArray().length - 1).getName()); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - } - } - - @SuppressWarnings("unchecked") - @Test - public final void whenSortingByStringNullFirst_thenFirstNull() { - service.create(new Foo()); - - final String jql = "Select f from Foo as f order by f.name desc NULLS FIRST"; - final Query sortQuery = entityManager.createQuery(jql); - final List fooList = sortQuery.getResultList(); - assertNull(fooList.get(0).getName()); - for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName()); - } - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java deleted file mode 100644 index 32a94ea3cb..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/FooStoredProceduresLiveTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.baeldung.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import com.baeldung.config.PersistenceConfig; -import com.baeldung.persistence.model.Foo; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.exception.SQLGrammarException; -import org.hibernate.query.NativeQuery; -import org.hibernate.query.Query; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -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.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooStoredProceduresLiveTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class); - - @Autowired - private SessionFactory sessionFactory; - - @Autowired - private FooService fooService; - - private Session session; - - @Before - public final void before() { - session = sessionFactory.openSession(); - Assume.assumeTrue(getAllFoosExists()); - Assume.assumeTrue(getFoosByNameExists()); - } - - private boolean getFoosByNameExists() { - try { - @SuppressWarnings("unchecked") - NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - sqlQuery.list(); - return true; - } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e); - return false; - } - } - - private boolean getAllFoosExists() { - try { - @SuppressWarnings("unchecked") - NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - sqlQuery.list(); - return true; - } catch (SQLGrammarException e) { - LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e); - return false; - } - } - - @After - public final void after() { - session.close(); - } - - @Test - public final void getAllFoosUsingStoredProcedures() { - - fooService.create(new Foo(randomAlphabetic(6))); - - // Stored procedure getAllFoos using createSQLQuery - @SuppressWarnings("unchecked") - NativeQuery sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class); - List allFoos = sqlQuery.list(); - for (Foo foo : allFoos) { - LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName()); - } - assertEquals(allFoos.size(), fooService.findAll().size()); - - // Stored procedure getAllFoos using a Named Query - @SuppressWarnings("unchecked") - Query namedQuery = session.getNamedQuery("callGetAllFoos"); - List allFoos2 = namedQuery.list(); - for (Foo foo : allFoos2) { - LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName()); - } - assertEquals(allFoos2.size(), fooService.findAll().size()); - } - - @Test - public final void getFoosByNameUsingStoredProcedures() { - - fooService.create(new Foo("NewFooName")); - - // Stored procedure getFoosByName using createSQLQuery() - @SuppressWarnings("unchecked") - Query sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName"); - List allFoosByName = sqlQuery.list(); - for (Foo foo : allFoosByName) { - LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString()); - } - - // Stored procedure getFoosByName using getNamedQuery() - @SuppressWarnings("unchecked") - Query namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName"); - List allFoosByName2 = namedQuery.list(); - for (Foo foo : allFoosByName2) { - LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString()); - } - - } -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java deleted file mode 100644 index 6f2a499bc5..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/FooTransactionalUnitTest.java +++ /dev/null @@ -1,250 +0,0 @@ -package com.baeldung.persistence.service.transactional; - -import com.baeldung.persistence.model.Foo; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; -import org.springframework.stereotype.Service; -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.IllegalTransactionStateException; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.transaction.support.TransactionTemplate; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceTransactionalTestConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -public class FooTransactionalUnitTest { - - static abstract class BasicFooDao { - @PersistenceContext private EntityManager entityManager; - - public Foo findOne(final long id) { - return entityManager.find(Foo.class, id); - } - - public Foo create(final Foo entity) { - entityManager.persist(entity); - return entity; - } - } - - @Repository - static class RequiredTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.REQUIRED) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class RequiresNewTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.REQUIRES_NEW) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class SupportTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.SUPPORTS) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class MandatoryTransactionalFooDao extends BasicFooDao { - @Override - @Transactional(propagation = Propagation.MANDATORY) - public Foo create(Foo entity) { - return super.create(entity); - } - } - - @Repository - static class SupportTransactionalFooService { - @Transactional(propagation = Propagation.SUPPORTS) - public Foo identity(Foo entity) { - return entity; - } - } - - @Service - static class MandatoryTransactionalFooService { - @Transactional(propagation = Propagation.MANDATORY) - public Foo identity(Foo entity) { - return entity; - } - } - - @Service - static class NotSupportedTransactionalFooService { - @Transactional(propagation = Propagation.NOT_SUPPORTED) - public Foo identity(Foo entity) { - return entity; - } - } - - @Service - static class NeverTransactionalFooService { - @Transactional(propagation = Propagation.NEVER) - public Foo identity(Foo entity) { - return entity; - } - } - - @Autowired private TransactionTemplate transactionTemplate; - - @Autowired private RequiredTransactionalFooDao requiredTransactionalFooDao; - - @Autowired private RequiresNewTransactionalFooDao requiresNewTransactionalFooDao; - - @Autowired private SupportTransactionalFooDao supportTransactionalFooDao; - - @Autowired private MandatoryTransactionalFooDao mandatoryTransactionalFooDao; - - @Autowired private MandatoryTransactionalFooService mandatoryTransactionalFooService; - - @Autowired private NeverTransactionalFooService neverTransactionalFooService; - - @Autowired private NotSupportedTransactionalFooService notSupportedTransactionalFooService; - - @Autowired private SupportTransactionalFooService supportTransactionalFooService; - - @After - public void tearDown(){ - PersistenceTransactionalTestConfig.clearSpy(); - } - - @Test - public void givenRequiredWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { - requiredTransactionalFooDao.create(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - - - @Test - public void givenRequiresNewWithNoActiveTransaction_whenCallCreate_thenExpect1NewAnd0Suspend() { - requiresNewTransactionalFooDao.create(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { - supportTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test(expected = IllegalTransactionStateException.class) - public void givenMandatoryWithNoActiveTransaction_whenCallService_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { - mandatoryTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test - public void givenNotSupportWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { - notSupportedTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test - public void givenNeverWithNoActiveTransaction_whenCallService_thenExpect0NewAnd0Suspend() { - neverTransactionalFooService.identity(new Foo("baeldung")); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(0, transactionSpy.getCreate()); - } - - @Test - public void givenRequiredWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return requiredTransactionalFooDao.create(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenRequiresNewWithActiveTransaction_whenCallCreate_thenExpect1NewAnd1Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return requiresNewTransactionalFooDao.create(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(1, transactionSpy.getSuspend()); - Assert.assertEquals(2, transactionSpy.getCreate()); - } - - @Test - public void givenSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return supportTransactionalFooDao.create(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenMandatoryWithActiveTransaction_whenCallCreate_thenExpect0NewAnd0Suspend() { - - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return mandatoryTransactionalFooDao.create(foo); - }); - - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test - public void givenNotSupportWithActiveTransaction_whenCallCreate_thenExpect0NewAnd1Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return notSupportedTransactionalFooService.identity(foo); - }); - - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(1, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - - @Test(expected = IllegalTransactionStateException.class) - public void givenNeverWithActiveTransaction_whenCallCreate_thenExpectIllegalTransactionStateExceptionWith0NewAnd0Suspend() { - transactionTemplate.execute(status -> { - Foo foo = new Foo("baeldung"); - return neverTransactionalFooService.identity(foo); - }); - PersistenceTransactionalTestConfig.TransactionSynchronizationAdapterSpy transactionSpy = PersistenceTransactionalTestConfig.getSpy(); - Assert.assertEquals(0, transactionSpy.getSuspend()); - Assert.assertEquals(1, transactionSpy.getCreate()); - } - -} diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java deleted file mode 100644 index 72031a2232..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/persistence/service/transactional/PersistenceTransactionalTestConfig.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.baeldung.persistence.service.transactional; - -import com.google.common.base.Preconditions; -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.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; -import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; -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.JpaVendorAdapter; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.transaction.support.DefaultTransactionStatus; -import org.springframework.transaction.support.TransactionSynchronizationAdapter; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionTemplate; - -@Configuration -@EnableTransactionManagement -@PropertySource({ "classpath:persistence-h2.properties" }) -@ComponentScan({ "com.baeldung.persistence","com.baeldung.jpa.dao" }) -@EnableJpaRepositories(basePackages = "com.baeldung.jpa.dao") -public class PersistenceTransactionalTestConfig { - - public static class TransactionSynchronizationAdapterSpy extends TransactionSynchronizationAdapter { - private int create, suspend; - - public int getSuspend() { - return suspend; - } - - public int getCreate() { - return create; - } - - public void create() { - create++; - } - - @Override - public void suspend() { - suspend++; - super.suspend(); - } - } - - - public static class JpaTransactionManagerSpy extends JpaTransactionManager { - @Override - protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) { - super.prepareSynchronization(status, definition); - if (status.isNewTransaction()) { - if ( adapterSpyThreadLocal.get() == null ){ - TransactionSynchronizationAdapterSpy spy = new TransactionSynchronizationAdapterSpy(); - TransactionSynchronizationManager.registerSynchronization(spy); - adapterSpyThreadLocal.set(spy); - } - adapterSpyThreadLocal.get().create(); - } - } - } - - private static ThreadLocal adapterSpyThreadLocal = new ThreadLocal<>(); - - @Autowired - private Environment env; - - public PersistenceTransactionalTestConfig() { - super(); - } - - public static TransactionSynchronizationAdapterSpy getSpy(){ - if ( adapterSpyThreadLocal.get() == null ) - return new TransactionSynchronizationAdapterSpy(); - return adapterSpyThreadLocal.get(); - } - - public static void clearSpy(){ - adapterSpyThreadLocal.set(null); - } - - // beans - - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() { - final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.persistence.model" }); - - final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); - em.setJpaVendorAdapter(vendorAdapter); - em.setJpaProperties(additionalProperties()); - - return em; - } - - @Bean - public DataSource dataSource() { - final DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); - dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); - dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); - dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); - - return dataSource; - } - - - - @Bean - public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) { - final JpaTransactionManagerSpy transactionManager = new JpaTransactionManagerSpy(); - transactionManager.setEntityManagerFactory(emf); - return transactionManager; - } - - @Bean - public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { - return new PersistenceExceptionTranslationPostProcessor(); - } - - 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.cache.use_second_level_cache", "false"); - return hibernateProperties; - } - - - @Bean - public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager){ - TransactionTemplate template = new TransactionTemplate(transactionManager); - template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); - return template; - } - - -} \ No newline at end of file diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java deleted file mode 100644 index 13b5b4357d..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryCommon.java +++ /dev/null @@ -1,555 +0,0 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.model.User; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -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.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.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.*; - - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) -@DirtiesContext -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); - - System.out.println(TimeZone.getDefault()); - - 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-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index c76e345fdd..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.spring.data.persistence.repository; - -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import com.baeldung.spring.data.persistence.model.User; -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 java.time.LocalDate; - -import static org.assertj.core.api.Assertions.assertThat; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.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-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java deleted file mode 100644 index 2bccada9fe..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/AbstractServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.baeldung.spring.data.persistence.service; - -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.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; - -import java.io.Serializable; -import java.util.List; - -import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.util.IDUtil; -import org.hamcrest.Matchers; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.dao.DataAccessException; - -import com.baeldung.persistence.dao.common.IOperations; - -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-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java deleted file mode 100644 index 8f628c5615..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/data/persistence/service/FooServicePersistenceIntegrationTest.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baeldung.spring.data.persistence.service; - -import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; -import static org.junit.Assert.assertNotNull; - -import com.baeldung.spring.data.persistence.model.Foo; -import com.baeldung.spring.data.persistence.config.PersistenceConfig; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -import com.baeldung.persistence.dao.common.IOperations; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.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-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleJNDIUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java similarity index 95% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleJNDIUnitTest.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java index 37f33b1192..6576962609 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleJNDIUnitTest.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jndi.datasource; +package com.baeldung.spring.jndi.datasource.mock; import static org.junit.Assert.assertEquals; diff --git a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleNamingContextBuilderManualTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleNamingContextBuilderManualTest.java similarity index 96% rename from persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleNamingContextBuilderManualTest.java rename to persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleNamingContextBuilderManualTest.java index ac33be1c6f..f4c3e012f9 100644 --- a/persistence-modules/spring-persistence-simple-2/src/test/java/com/baeldung/jndi/datasource/SimpleNamingContextBuilderManualTest.java +++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleNamingContextBuilderManualTest.java @@ -1,4 +1,4 @@ -package com.baeldung.jndi.datasource; +package com.baeldung.spring.jndi.datasource.mock; import static org.junit.Assert.assertNotNull; diff --git a/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore b/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/persistence-modules/spring-persistence-simple/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/pom.xml b/pom.xml index ffdfe4cffa..a2e09c0f91 100644 --- a/pom.xml +++ b/pom.xml @@ -655,9 +655,7 @@ spring-ejb spring-exceptions - spring-freemarker - - spring-groovy + spring-freemarker spring-integration @@ -1159,9 +1157,7 @@ spring-ejb spring-exceptions - spring-freemarker - - spring-groovy + spring-freemarker spring-integration diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index c9917d14df..317cbde6e2 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -34,7 +34,7 @@ - 3.2.6.RELEASE + 3.3.9.RELEASE 3.6.1 diff --git a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java b/reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java similarity index 91% rename from reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java rename to reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java index e3060b8e02..a1acffac91 100644 --- a/reactor-core/src/test/java/com/baeldung/reactor/ReactorIntegrationTest.java +++ b/reactor-core/src/test/java/com/baeldung/reactor/introduction/ReactorIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.reactor; +package com.baeldung.reactor.introduction; import org.junit.Test; import org.reactivestreams.Subscriber; @@ -15,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; public class ReactorIntegrationTest { @Test - public void givenFlux_whenSubscribing_thenStream() throws InterruptedException { + public void givenFlux_whenSubscribing_thenStream() { List elements = new ArrayList<>(); @@ -48,14 +48,12 @@ public class ReactorIntegrationTest { } @Test - public void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() throws InterruptedException { + public void givenFlux_whenApplyingBackPressure_thenPushElementsInBatches() { List elements = new ArrayList<>(); Flux.just(1, 2, 3, 4) .log() - .map(i -> i * 2) - .onBackpressureBuffer() .subscribe(new Subscriber() { private Subscription s; int onNextAmount; @@ -81,11 +79,10 @@ public class ReactorIntegrationTest { @Override public void onComplete() { - int ham = 2; } }); - assertThat(elements).containsExactly(2, 4, 6, 8); + assertThat(elements).containsExactly(1, 2, 3, 4); } @Test diff --git a/spring-4/pom.xml b/spring-4/pom.xml index b6b8deb273..cd6b232317 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -8,6 +8,7 @@ jar + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-activiti/pom.xml b/spring-activiti/pom.xml index 4803827b45..a8557b4f56 100644 --- a/spring-activiti/pom.xml +++ b/spring-activiti/pom.xml @@ -8,6 +8,7 @@ Demo project for Spring Boot + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-boot-groovy/README.md b/spring-boot-groovy/README.md deleted file mode 100644 index d2472a11d0..0000000000 --- a/spring-boot-groovy/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Building a Simple Web Application with Spring Boot and Groovy](https://www.baeldung.com/spring-boot-groovy-web-app) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index b4cabaaedf..527f7dcad8 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -41,6 +41,7 @@ spring-boot-environment spring-boot-exceptions spring-boot-flowable + spring-boot-groovy spring-boot-jasypt spring-boot-keycloak @@ -61,6 +62,7 @@ spring-boot-runtime spring-boot-security spring-boot-springdoc + spring-boot-swagger spring-boot-testing spring-boot-vue spring-boot-xml diff --git a/spring-boot-modules/spring-boot-1/pom.xml b/spring-boot-modules/spring-boot-1/pom.xml index 145bb221e0..d44120b21e 100644 --- a/spring-boot-modules/spring-boot-1/pom.xml +++ b/spring-boot-modules/spring-boot-1/pom.xml @@ -7,6 +7,7 @@ Module for Spring Boot version 1.x + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-actuator/README.MD b/spring-boot-modules/spring-boot-actuator/README.md similarity index 72% rename from spring-boot-modules/spring-boot-actuator/README.MD rename to spring-boot-modules/spring-boot-actuator/README.md index fbb4dfba0f..6f31ee4a5e 100644 --- a/spring-boot-modules/spring-boot-actuator/README.MD +++ b/spring-boot-modules/spring-boot-actuator/README.md @@ -8,3 +8,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [Liveness and Readiness Probes in Spring Boot](https://www.baeldung.com/spring-liveness-readiness-probes) +- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) diff --git a/spring-boot-modules/spring-boot-actuator/pom.xml b/spring-boot-modules/spring-boot-actuator/pom.xml index 701949519e..18da6d3a9a 100644 --- a/spring-boot-modules/spring-boot-actuator/pom.xml +++ b/spring-boot-modules/spring-boot-actuator/pom.xml @@ -24,6 +24,14 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java new file mode 100644 index 0000000000..75a7182b3c --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.endpoints.info; + +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/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java similarity index 94% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java rename to spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java index c316cabda5..a685660b4f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/TotalUsersInfoContributor.java @@ -3,7 +3,6 @@ package com.baeldung.endpoints.info; import java.util.HashMap; import java.util.Map; -import com.baeldung.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java new file mode 100644 index 0000000000..db4e69127a --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/User.java @@ -0,0 +1,49 @@ +package com.baeldung.endpoints.info; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Integer id; + private String name; + private Integer status; + + public User() { + } + + public User(String name, Integer status) { + this.name = name; + this.status = status; + } + + 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 getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java new file mode 100644 index 0000000000..8af5ef3988 --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/info/UserRepository.java @@ -0,0 +1,78 @@ +package com.baeldung.endpoints.info; + +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 org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Repository; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; + +@Repository("userRepository") +public interface UserRepository extends JpaRepository { + + int countByStatus(int status); + + Optional findOneByName(String name); + + @Async + CompletableFuture findOneByStatus(Integer status); + + @Query("SELECT u FROM User u WHERE u.status = 1") + Collection findAllActiveUsers(); + + @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 \n-- #pageable\n", 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); + +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties index 27dba985b8..00100d6d97 100644 --- a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties @@ -2,4 +2,10 @@ management.health.probes.enabled=true management.endpoint.health.show-details=always management.endpoint.health.status.http-mapping.down=500 management.endpoint.health.status.http-mapping.out_of_service=503 -management.endpoint.health.status.http-mapping.warning=500 \ No newline at end of file +management.endpoint.health.status.http-mapping.warning=500 + +## Configuring info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application G1 +info.app.version=1.0.0 +info.java-vendor = ${java.specification.vendor} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/pom.xml b/spring-boot-modules/spring-boot-camel/pom.xml index 881b021b96..46a90b4722 100644 --- a/spring-boot-modules/spring-boot-camel/pom.xml +++ b/spring-boot-modules/spring-boot-camel/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -38,12 +38,10 @@ org.springframework.boot spring-boot-starter-web - ${spring-boot-starter.version} org.springframework.boot spring-boot-starter-test - ${spring-boot-starter.version} test @@ -55,7 +53,6 @@ org.springframework.boot spring-boot-maven-plugin - ${spring-boot-starter.version} @@ -68,8 +65,7 @@ - 2.19.1 - 1.5.4.RELEASE + 3.0.0-M4 diff --git a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java index aadd37a3b4..48294e9c56 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java +++ b/spring-boot-modules/spring-boot-camel/src/main/java/com/baeldung/camel/Application.java @@ -12,33 +12,36 @@ import org.apache.camel.model.rest.RestBindingMode; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.aop.AopAutoConfiguration; +import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration; +import org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration; +import org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; -@SpringBootApplication -@ComponentScan(basePackages="com.baeldung.camel") -public class Application{ +@SpringBootApplication(exclude = { WebSocketServletAutoConfiguration.class, AopAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, EmbeddedWebServerFactoryCustomizerAutoConfiguration.class }) +@ComponentScan(basePackages = "com.baeldung.camel") +public class Application { @Value("${server.port}") String serverPort; - + @Value("${baeldung.api.path}") String contextPath; - + public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean ServletRegistrationBean servletRegistrationBean() { - ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath+"/*"); + ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath + "/*"); servlet.setName("CamelServlet"); return servlet; } - @Component class RestApi extends RouteBuilder { @@ -47,7 +50,6 @@ public class Application{ CamelContext context = new DefaultCamelContext(); - // http://localhost:8080/camel/api-doc restConfiguration().contextPath(contextPath) // .port(serverPort) @@ -60,43 +62,43 @@ public class Application{ .component("servlet") .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); -/** -The Rest DSL supports automatic binding json/xml contents to/from -POJOs using Camels Data Format. -By default the binding mode is off, meaning there is no automatic -binding happening for incoming and outgoing messages. -You may want to use binding if you develop POJOs that maps to -your REST services request and response types. -*/ - + /** + The Rest DSL supports automatic binding json/xml contents to/from + POJOs using Camels Data Format. + By default the binding mode is off, meaning there is no automatic + binding happening for incoming and outgoing messages. + You may want to use binding if you develop POJOs that maps to + your REST services request and response types. + */ + rest("/api/").description("Teste REST Service") .id("api-route") .post("/bean") .produces(MediaType.APPLICATION_JSON) .consumes(MediaType.APPLICATION_JSON) -// .get("/hello/{place}") + // .get("/hello/{place}") .bindingMode(RestBindingMode.auto) .type(MyBean.class) .enableCORS(true) -// .outType(OutBean.class) + // .outType(OutBean.class) .to("direct:remoteService"); - - - from("direct:remoteService") - .routeId("direct-route") + + from("direct:remoteService").routeId("direct-route") .tracing() .log(">>> ${body.id}") .log(">>> ${body.name}") -// .transform().simple("blue ${in.body.name}") + // .transform().simple("blue ${in.body.name}") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { - MyBean bodyIn = (MyBean) exchange.getIn().getBody(); - + MyBean bodyIn = (MyBean) exchange.getIn() + .getBody(); + ExampleServices.example(bodyIn); - exchange.getIn().setBody(bodyIn); + exchange.getIn() + .setBody(bodyIn); } }) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)); diff --git a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties index bce95f8eaf..29fee8cff6 100644 --- a/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-camel/src/main/resources/application.properties @@ -12,4 +12,6 @@ management.port=8081 # disable all management enpoints except health endpoints.enabled = true -endpoints.health.enabled = true \ No newline at end of file +endpoints.health.enabled = true + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-camel/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-camel/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot-di/README.MD b/spring-boot-modules/spring-boot-di/README.md similarity index 81% rename from spring-boot-modules/spring-boot-di/README.MD rename to spring-boot-modules/spring-boot-di/README.md index cbd42c5609..2759c73926 100644 --- a/spring-boot-modules/spring-boot-di/README.MD +++ b/spring-boot-modules/spring-boot-di/README.md @@ -9,3 +9,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Component Scanning](https://www.baeldung.com/spring-component-scanning) - [Spring @ComponentScan – Filter Types](https://www.baeldung.com/spring-componentscan-filter-type) +- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) diff --git a/spring-boot-modules/spring-boot-di/pom.xml b/spring-boot-modules/spring-boot-di/pom.xml index 87a0ad2937..58b427a4a8 100644 --- a/spring-boot-modules/spring-boot-di/pom.xml +++ b/spring-boot-modules/spring-boot-di/pom.xml @@ -27,6 +27,12 @@ org.springframework.boot spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + org.springframework.boot spring-boot-starter-tomcat diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/Application.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/Application.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/Application.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/controller/FooController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/controller/FooController.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/controller/FooController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java b/spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/service/FooService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/displayallbeans/service/FooService.java rename to spring-boot-modules/spring-boot-di/src/main/java/com/baeldung/displayallbeans/service/FooService.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot-modules/spring-boot-di/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java rename to spring-boot-modules/spring-boot-di/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-groovy/README.md b/spring-boot-modules/spring-boot-groovy/README.md new file mode 100644 index 0000000000..73edafb9c0 --- /dev/null +++ b/spring-boot-modules/spring-boot-groovy/README.md @@ -0,0 +1,9 @@ +## Spring Boot Groovy + +This module contains articles about Spring with Groovy + + +### Relevant Articles: + +- [Building a Simple Web Application with Spring Boot and Groovy](https://www.baeldung.com/spring-boot-groovy-web-app) +- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) \ No newline at end of file diff --git a/spring-boot-groovy/pom.xml b/spring-boot-modules/spring-boot-groovy/pom.xml similarity index 94% rename from spring-boot-groovy/pom.xml rename to spring-boot-modules/spring-boot-groovy/pom.xml index 9ea8d7b2a9..3392532081 100644 --- a/spring-boot-groovy/pom.xml +++ b/spring-boot-modules/spring-boot-groovy/pom.xml @@ -14,7 +14,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 @@ -72,7 +72,7 @@ - com.baeldung.app.SpringBootGroovyApplication + com.baeldung.springwithgroovy.SpringBootGroovyApplication diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/SpringBootGroovyApplication.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/controller/TodoController.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/entity/Todo.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/repository/TodoRepository.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/TodoService.groovy diff --git a/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy b/spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy similarity index 100% rename from spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/groovy/com/baeldung/springwithgroovy/service/impl/TodoServiceImpl.groovy diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/BandsBean.java similarity index 89% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/BandsBean.java index 1deba5d2f6..29f143c66c 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/BandsBean.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/BandsBean.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import java.util.ArrayList; import java.util.List; diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/GroovyBeanConfig.groovy similarity index 90% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/GroovyBeanConfig.groovy index 32a6fedff0..3237226877 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/GroovyBeanConfig.groovy +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/GroovyBeanConfig.groovy @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; beans { javaPesronBean(JavaPersonBean) { diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaBeanConfig.java similarity index 93% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaBeanConfig.java index 7c4238ae28..64926f606b 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaBeanConfig.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaBeanConfig.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaPersonBean.java similarity index 96% rename from spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaPersonBean.java index db988d4abf..da0b92451e 100644 --- a/spring-groovy/src/main/java/com/baeldug/groovyconfig/JavaPersonBean.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/groovyconfig/JavaPersonBean.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; public class JavaPersonBean { diff --git a/spring-groovy/src/main/java/com/baeldug/spring_groovy/App.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/App.java similarity index 80% rename from spring-groovy/src/main/java/com/baeldug/spring_groovy/App.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/App.java index 1df6681c42..2465683c5f 100644 --- a/spring-groovy/src/main/java/com/baeldug/spring_groovy/App.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/App.java @@ -1,4 +1,4 @@ -package com.baeldug.spring_groovy; +package com.baeldung.spring_groovy; /** * Hello world! diff --git a/spring-groovy/src/main/java/com/baeldug/spring_groovy/TestConfig.java b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/TestConfig.java similarity index 71% rename from spring-groovy/src/main/java/com/baeldug/spring_groovy/TestConfig.java rename to spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/TestConfig.java index 474216de4e..04ff38c475 100644 --- a/spring-groovy/src/main/java/com/baeldug/spring_groovy/TestConfig.java +++ b/spring-boot-modules/spring-boot-groovy/src/main/java/com/baeldung/spring_groovy/TestConfig.java @@ -1,4 +1,4 @@ -package com.baeldug.spring_groovy; +package com.baeldung.spring_groovy; import org.springframework.stereotype.Component; diff --git a/spring-boot-groovy/src/main/resources/application.properties b/spring-boot-modules/spring-boot-groovy/src/main/resources/application.properties similarity index 100% rename from spring-boot-groovy/src/main/resources/application.properties rename to spring-boot-modules/spring-boot-groovy/src/main/resources/application.properties diff --git a/spring-groovy/src/main/resources/groovyContextConfig.groovy b/spring-boot-modules/spring-boot-groovy/src/main/resources/groovyContextConfig.groovy similarity index 100% rename from spring-groovy/src/main/resources/groovyContextConfig.groovy rename to spring-boot-modules/spring-boot-groovy/src/main/resources/groovyContextConfig.groovy diff --git a/spring-groovy/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-groovy/src/main/resources/logback.xml similarity index 100% rename from spring-groovy/src/main/resources/logback.xml rename to spring-boot-modules/spring-boot-groovy/src/main/resources/logback.xml diff --git a/spring-groovy/src/main/resources/xml-bean-config.xml b/spring-boot-modules/spring-boot-groovy/src/main/resources/xml-bean-config.xml similarity index 87% rename from spring-groovy/src/main/resources/xml-bean-config.xml rename to spring-boot-modules/spring-boot-groovy/src/main/resources/xml-bean-config.xml index 3b880bbd70..b26f28f7b1 100644 --- a/spring-groovy/src/main/resources/xml-bean-config.xml +++ b/spring-boot-modules/spring-boot-groovy/src/main/resources/xml-bean-config.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy b/spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy similarity index 93% rename from spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy rename to spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy index bf8b0ff27f..6ae6ffcd73 100644 --- a/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppUnitTest.groovy +++ b/spring-boot-modules/spring-boot-groovy/src/test/groovy/com/baeldung/springwithgroovy/TodoAppLiveTest.groovy @@ -17,8 +17,11 @@ import com.baeldung.springwithgroovy.entity.Todo import io.restassured.RestAssured import io.restassured.response.Response -class TodoAppUnitTest { - static API_ROOT = 'http://localhost:8081/todo' +// This test requires the com.baeldung.springwithgroovy.SpringBootGroovyApplication to be up +// For that, run the maven build - spring-boot:run on the module + +class TodoAppLiveTest { + static API_ROOT = 'http://localhost:8080/todo' static readingTodoId static writingTodoId diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/GroovyConfigurationUnitTest.java similarity index 90% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/GroovyConfigurationUnitTest.java index dbefba5ba5..bd46ded977 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/GroovyConfigurationUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/GroovyConfigurationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import static org.junit.Assert.assertEquals; @@ -7,10 +7,13 @@ import java.io.File; import org.junit.Test; import org.springframework.context.support.GenericGroovyApplicationContext; +import com.baeldung.groovyconfig.BandsBean; +import com.baeldung.groovyconfig.JavaPersonBean; + public class GroovyConfigurationUnitTest { private static final String FILE_NAME = "GroovyBeanConfig.groovy"; - private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/"; + private static final String FILE_PATH = "src/main/java/com/baeldung/groovyconfig/"; @Test public void whenGroovyConfig_thenCorrectPerson() throws Exception { diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/JavaConfigurationUnitTest.java similarity index 82% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/JavaConfigurationUnitTest.java index c1e16f1b62..2ab1998853 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/JavaConfigurationUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/JavaConfigurationUnitTest.java @@ -1,10 +1,13 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import com.baeldung.groovyconfig.JavaBeanConfig; +import com.baeldung.groovyconfig.JavaPersonBean; + public class JavaConfigurationUnitTest { @Test diff --git a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/XmlConfigurationUnitTest.java similarity index 88% rename from spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/XmlConfigurationUnitTest.java index b8d341ee39..aa9f3bd8f7 100644 --- a/spring-groovy/src/test/java/com/baeldug/groovyconfig/XmlConfigurationUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/groovyconfig/XmlConfigurationUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldug.groovyconfig; +package com.baeldung.groovyconfig; import static org.junit.Assert.*; @@ -6,6 +6,8 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import com.baeldung.groovyconfig.JavaPersonBean; + public class XmlConfigurationUnitTest { @Test diff --git a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/spring_groovy/AppUnitTest.java similarity index 94% rename from spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java rename to spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/spring_groovy/AppUnitTest.java index 3d8fa3e2d8..9702e98ab8 100644 --- a/spring-groovy/src/test/java/com/baeldug/spring_groovy/AppUnitTest.java +++ b/spring-boot-modules/spring-boot-groovy/src/test/java/com/baeldung/spring_groovy/AppUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldug.spring_groovy; +package com.baeldung.spring_groovy; import junit.framework.Test; import junit.framework.TestCase; diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java new file mode 100644 index 0000000000..1959590e5a --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/CustomUserAttrController.java @@ -0,0 +1,46 @@ +package com.baeldung.keycloak; + +import java.security.Principal; +import java.util.Map; + +import org.keycloak.KeycloakPrincipal; +import org.keycloak.KeycloakSecurityContext; +import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken; +import org.keycloak.representations.IDToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class CustomUserAttrController { + + @GetMapping(path = "/users") + public String getUserInfo(Model model) { + + KeycloakAuthenticationToken authentication = (KeycloakAuthenticationToken) SecurityContextHolder.getContext() + .getAuthentication(); + + final Principal principal = (Principal) authentication.getPrincipal(); + + String dob = ""; + + if (principal instanceof KeycloakPrincipal) { + + KeycloakPrincipal kPrincipal = (KeycloakPrincipal) principal; + IDToken token = kPrincipal.getKeycloakSecurityContext() + .getIdToken(); + + Map customClaims = token.getOtherClaims(); + + if (customClaims.containsKey("DOB")) { + dob = String.valueOf(customClaims.get("DOB")); + } + } + + model.addAttribute("username", principal.getName()); + model.addAttribute("dob", dob); + return "userInfo"; + } + +} diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 4ecb62b6d4..895ac8c562 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -44,7 +44,7 @@ class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { super.configure(http); http.authorizeRequests() - .antMatchers("/customers*") + .antMatchers("/customers*", "/users*") .hasRole("user") .anyRequest() .permitAll(); diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html new file mode 100644 index 0000000000..1446fe2124 --- /dev/null +++ b/spring-boot-modules/spring-boot-keycloak/src/main/resources/templates/userInfo.html @@ -0,0 +1,15 @@ + + + + + +
+

+ Hello, --name--. +

+

+ Your Date of Birth as per our records is . +

+
+ + diff --git a/spring-boot-modules/spring-boot-libraries/README.md b/spring-boot-modules/spring-boot-libraries/README.md index 8cd3db9c93..10c56ca576 100644 --- a/spring-boot-modules/spring-boot-libraries/README.md +++ b/spring-boot-modules/spring-boot-libraries/README.md @@ -12,3 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Generating Barcodes and QR Codes in Java](https://www.baeldung.com/java-generating-barcodes-qr-codes) - [Rate Limiting a Spring API Using Bucket4j](https://www.baeldung.com/spring-bucket4j) - [Spring Boot and Caffeine Cache](https://www.baeldung.com/spring-boot-caffeine-cache) +- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) +- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) +- [An Introduction to Kong](https://www.baeldung.com/kong) diff --git a/spring-boot-modules/spring-boot-libraries/pom.xml b/spring-boot-modules/spring-boot-libraries/pom.xml index 05ab59aab7..3913babaa8 100644 --- a/spring-boot-modules/spring-boot-libraries/pom.xml +++ b/spring-boot-modules/spring-boot-libraries/pom.xml @@ -37,6 +37,36 @@ spring-boot-starter-test test + + + + org.togglz + togglz-spring-boot-starter + ${togglz.version} + + + + org.togglz + togglz-spring-security + ${togglz.version} + + + + + com.graphql-java + graphql-spring-boot-starter + ${graphql-spring-boot-starter.version} + + + com.graphql-java + graphql-java-tools + ${graphql-java-tools.version} + + + com.graphql-java + graphiql-spring-boot-starter + ${graphql-spring-boot-starter.version} + @@ -216,7 +246,6 @@ 1.9.0 2.0.0 5.0.2 - 5.0.2 5.2.4 18.0 2.2.4 diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java new file mode 100644 index 0000000000..eb091b4695 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/demo/DemoApplication.java @@ -0,0 +1,18 @@ +package com.baeldung.demo; + +import com.baeldung.graphql.GraphqlConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import org.springframework.context.annotation.Import; + +@SpringBootApplication +@Import(GraphqlConfiguration.class) +public class DemoApplication { + + public static void main(String[] args) { + System.setProperty("spring.config.name", "demo"); + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Author.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Author.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Author.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorDao.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorDao.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorDao.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorResolver.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/AuthorResolver.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/AuthorResolver.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/GraphqlConfiguration.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Mutation.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Mutation.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Mutation.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Post.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Post.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Post.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostDao.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostDao.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostDao.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostResolver.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/PostResolver.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/PostResolver.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Query.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/graphql/Query.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/graphql/Query.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/QueryController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/QueryController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/QueryController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/StockApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/kong/StockApp.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/kong/StockApp.java diff --git a/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java new file mode 100644 index 0000000000..64a8b3ce5b --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/Employee.java @@ -0,0 +1,37 @@ +package com.baeldung.toggle; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + private long id; + private double salary; + + public Employee() { + } + + public Employee(long id, double salary) { + this.id = id; + this.salary = salary; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + +} diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/EmployeeRepository.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/EmployeeRepository.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/EmployeeRepository.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeatureAssociation.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeatureAssociation.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeatureAssociation.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeaturesAspect.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/FeaturesAspect.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/FeaturesAspect.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/MyFeatures.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/MyFeatures.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/MyFeatures.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryController.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryController.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryController.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryService.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/SalaryService.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/SalaryService.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleApplication.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleApplication.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java b/spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/toggle/ToggleConfiguration.java rename to spring-boot-modules/spring-boot-libraries/src/main/java/com/baeldung/toggle/ToggleConfiguration.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/APIObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/APIObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/ConsumerObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/ConsumerObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/KeyAuthObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/PluginObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/PluginObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/TargetObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/TargetObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/kong/domain/UpstreamObject.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/kong/domain/UpstreamObject.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java b/spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java rename to spring-boot-modules/spring-boot-libraries/src/test/java/com/baeldung/toggle/ToggleIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc/README.md b/spring-boot-modules/spring-boot-mvc/README.md index 41b98063a6..5e9ecded10 100644 --- a/spring-boot-modules/spring-boot-mvc/README.md +++ b/spring-boot-modules/spring-boot-mvc/README.md @@ -9,4 +9,6 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [A Controller, Service and DAO Example with Spring Boot and JSF](https://www.baeldung.com/jsf-spring-boot-controller-service-dao) - [Setting Up Swagger 2 with a Spring REST API](https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api) - [Using Spring ResponseEntity to Manipulate the HTTP Response](https://www.baeldung.com/spring-response-entity) +- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) +- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - More articles: [[next -->]](/spring-boot-modules/spring-boot-mvc-2) diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 39046ee6d9..560ea1cffa 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -17,15 +17,6 @@ spring-boot-mvc Module For Spring Boot MVC - - - - jcenter-release - jcenter - http://oss.jfrog.org/artifactory/oss-release-local/ - - - diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootAnnotatedApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/SpringBootPlainApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/AttrListener.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/EchoServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloFilter.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/annotation/servletcomponentscan/components/HelloServlet.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/InternationalizationApp.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/InternationalizationApp.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/MvcConfig.java similarity index 100% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/MvcConfig.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/MvcConfig.java diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java similarity index 87% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java rename to spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java index 96a534b853..efa55b8b33 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/internationalization/config/PageController.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/internationalization/config/PageController.java @@ -8,7 +8,7 @@ public class PageController { @GetMapping("/international") public String getInternationalPage() { - return "international"; + return "thymeleaf/international"; } } diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java index b404b0c2f8..5998ffeb2a 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/swagger2boot/configuration/SpringFoxConfig.java @@ -22,7 +22,6 @@ import springfox.documentation.swagger.web.UiConfigurationBuilder; import java.util.Collections; @Configuration -@Import({SpringDataRestConfiguration.class, BeanValidatorPluginsConfiguration.class}) public class SpringFoxConfig { private ApiInfo apiInfo() { diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties index 9794c89651..8f956fe5be 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages.properties @@ -1 +1,5 @@ -email.notempty=Please provide valid email id. \ No newline at end of file +email.notempty=Please provide valid email id. +greeting=Hello! Welcome to our website! +lang.change=Change the language +lang.eng=English +lang.fr=French \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties index 070f4e0bfc..7ced0d7b0d 100644 --- a/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/messages_fr.properties @@ -1 +1,5 @@ -email.notempty=Veuillez fournir un identifiant de messagerie valide. \ No newline at end of file +email.notempty=Veuillez fournir un identifiant de messagerie valide. +greeting=Bonjour! Bienvenue sur notre site! +lang.change=Changez la langue +lang.eng=Anglais +lang.fr=Francais diff --git a/spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js b/spring-boot-modules/spring-boot-mvc/src/main/resources/static/internationalization.js similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/static/internationalization.js rename to spring-boot-modules/spring-boot-mvc/src/main/resources/static/internationalization.js diff --git a/spring-boot-modules/spring-boot/src/main/resources/templates/international.html b/spring-boot-modules/spring-boot-mvc/src/main/resources/templates/thymeleaf/international.html similarity index 100% rename from spring-boot-modules/spring-boot/src/main/resources/templates/international.html rename to spring-boot-modules/spring-boot-mvc/src/main/resources/templates/thymeleaf/international.html diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextLiveTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextLiveTest.java diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextTest.java similarity index 100% rename from spring-boot-modules/spring-boot-mvc/src/test/java/org/baeldung/SpringContextTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/SpringContextTest.java diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 8c85934fac..92223892d9 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -1,23 +1,21 @@ package com.baeldung.annotation.servletcomponentscan; -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.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; + +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.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) public class SpringBootWithServletComponentIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml index 7d900d8ea8..73dd672c1a 100644 --- a/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml +++ b/spring-boot-modules/spring-boot-security/src/main/resources/logback.xml @@ -7,7 +7,7 @@ - + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-security/src/test/resources/application.properties b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties new file mode 100644 index 0000000000..5494069009 --- /dev/null +++ b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties @@ -0,0 +1,2 @@ +logging.level.root=ERROR +logging.level.com.baeldung.integrationtesting=ERROR diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml b/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-boot-modules/spring-boot-springdoc/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml new file mode 100644 index 0000000000..4e0180460d --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + + + com.baeldung.spring-boot-modules + spring-boot-modules + 1.0.0-SNAPSHOT + ../ + + + spring-boot-swagger + 0.1.0-SNAPSHOT + spring-boot-swagger + jar + + Module For Spring Boot Swagger + + + org.springframework.boot + spring-boot-starter-web + + + io.springfox + springfox-boot-starter + 3.0.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java new file mode 100644 index 0000000000..911c29a4f6 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/SpringBootSwaggerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.swagger2boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootSwaggerApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringBootSwaggerApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java new file mode 100644 index 0000000000..4f85d90f5f --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/configuration/SwaggerConfiguration.java @@ -0,0 +1,63 @@ +package com.baeldung.swagger2boot.configuration; + +import java.util.Collections; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger.web.DocExpansion; +import springfox.documentation.swagger.web.ModelRendering; +import springfox.documentation.swagger.web.OperationsSorter; +import springfox.documentation.swagger.web.TagsSorter; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; + +@Configuration +public class SwaggerConfiguration { + + private ApiInfo apiInfo() { + return new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", + new Contact("Umang Budhwar", "www.baeldung.com", "umangbudhwar@gmail.com"), + "License of API", "API license URL", Collections.emptyList()); + } + + @Bean + public Docket api() { + return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build(); + } + + /** + * SwaggerUI information + */ + + @Bean + UiConfiguration uiConfig() { + return UiConfigurationBuilder.builder() + .deepLinking(true) + .displayOperationId(false) + .defaultModelsExpandDepth(1) + .defaultModelExpandDepth(1) + .defaultModelRendering(ModelRendering.EXAMPLE) + .displayRequestDuration(false) + .docExpansion(DocExpansion.NONE) + .filter(false) + .maxDisplayedTags(null) + .operationsSorter(OperationsSorter.ALPHA) + .showExtensions(false) + .tagsSorter(TagsSorter.ALPHA) + .supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS) + .validatorUrl(null) + .build(); + } + +} diff --git a/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java new file mode 100644 index 0000000000..5218092c21 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger/src/main/java/com/baeldung/swagger2boot/controller/RegularRestController.java @@ -0,0 +1,35 @@ +package com.baeldung.swagger2boot.controller; + +import java.time.LocalDate; +import java.time.LocalTime; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import io.swagger.annotations.ApiOperation; +import springfox.documentation.annotations.ApiIgnore; + +@ApiIgnore +@RestController +public class RegularRestController { + + @ApiIgnore + @ApiOperation(value = "This method is used to get the author name.") + @GetMapping("/getAuthor") + public String getAuthor() { + return "Umang Budhwar"; + } + + @ApiOperation(value = "This method is used to get the current date.", hidden = true) + @GetMapping("/getDate") + public LocalDate getDate() { + return LocalDate.now(); + } + + @ApiOperation(value = "This method is used to get the current time.") + @GetMapping("/getTime") + public LocalTime getTime() { + return LocalTime.now(); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties b/spring-boot-modules/spring-boot-swagger/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-testing/README.md b/spring-boot-modules/spring-boot-testing/README.md index 192f5cee99..1b7ad661c6 100644 --- a/spring-boot-modules/spring-boot-testing/README.md +++ b/spring-boot-modules/spring-boot-testing/README.md @@ -14,3 +14,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) - [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) - [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) +- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml index a3b176af88..bd5ef901dd 100644 --- a/spring-boot-modules/spring-boot-testing/pom.xml +++ b/spring-boot-modules/spring-boot-testing/pom.xml @@ -34,6 +34,14 @@ org.springframework.boot spring-boot-starter-security + + org.springframework.boot + spring-boot-starter-data-jpa + + + com.h2database + h2 + org.springframework.boot spring-boot-starter-test diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java similarity index 95% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java index fa3c1dc809..2921ecc609 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/Employee.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/Employee.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java similarity index 91% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java index b6850d587e..bcef5231e0 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRepository.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java index 7d2e06d4a0..b52d38e028 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeRestController.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeRestController.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java similarity index 89% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java index ff1976cad1..6fc48a3c3d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeService.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeService.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java similarity index 96% rename from spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java rename to spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java index 156fc571f3..7d5ec4a05d 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/boottest/EmployeeServiceImpl.java +++ b/spring-boot-modules/spring-boot-testing/src/main/java/com/baeldung/boot/testing/EmployeeServiceImpl.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import java.util.List; diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties index 8dc7f6e3c3..daab3e8d2c 100644 --- a/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/application.properties @@ -4,4 +4,6 @@ spring.redis.port= 6379 # security spring.security.user.name=john -spring.security.user.password=123 \ No newline at end of file +spring.security.user.password=123 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties new file mode 100644 index 0000000000..b19304cb1f --- /dev/null +++ b/spring-boot-modules/spring-boot-testing/src/main/resources/persistence-generic-entity.properties @@ -0,0 +1,8 @@ +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.show_sql=true +hibernate.hbm2ddl.auto=create-drop diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java index 962abf0fa3..c51113a023 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeControllerIntegrationTest.java @@ -1,19 +1,4 @@ -package com.baeldung.demo.boottest; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.internal.verification.VerificationModeFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.MediaType; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Arrays; -import java.util.List; +package com.baeldung.boot.testing; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; @@ -25,8 +10,28 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.internal.verification.VerificationModeFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRestController; +import com.baeldung.boot.testing.EmployeeService; + @RunWith(SpringRunner.class) -@WebMvcTest(EmployeeRestController.class) +@WebMvcTest(value = EmployeeRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class) public class EmployeeControllerIntegrationTest { @Autowired diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java index 164887886b..b3a7316764 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRepositoryIntegrationTest.java @@ -1,7 +1,5 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; -import com.baeldung.demo.boottest.Employee; -import com.baeldung.demo.boottest.EmployeeRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -9,6 +7,9 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; + import java.util.List; import static org.assertj.core.api.Assertions.assertThat; diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java similarity index 87% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java index 327e9f9d56..d13fcd79aa 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeRestControllerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeRestControllerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.is; @@ -14,11 +14,12 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.io.IOException; import java.util.List; -import com.baeldung.demo.DemoApplication; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; @@ -27,9 +28,14 @@ import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import com.baeldung.boot.Application; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; + @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = DemoApplication.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = Application.class) @AutoConfigureMockMvc +@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class) // @TestPropertySource(locations = "classpath:application-integrationtest.properties") @AutoConfigureTestDatabase public class EmployeeRestControllerIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java similarity index 94% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java index 88f2830a2b..3176a7c75a 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/EmployeeServiceImplIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/EmployeeServiceImplIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import static org.assertj.core.api.Assertions.assertThat; @@ -6,10 +6,6 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; -import com.baeldung.demo.boottest.Employee; -import com.baeldung.demo.boottest.EmployeeRepository; -import com.baeldung.demo.boottest.EmployeeService; -import com.baeldung.demo.boottest.EmployeeServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -21,6 +17,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.boot.testing.Employee; +import com.baeldung.boot.testing.EmployeeRepository; +import com.baeldung.boot.testing.EmployeeService; +import com.baeldung.boot.testing.EmployeeServiceImpl; + @RunWith(SpringRunner.class) public class EmployeeServiceImplIntegrationTest { diff --git a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java similarity index 91% rename from spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java rename to spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java index 3fcd709f7c..49d018dde8 100644 --- a/spring-boot-modules/spring-boot/src/test/java/com/baeldung/demo/boottest/JsonUtil.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/testing/JsonUtil.java @@ -1,4 +1,4 @@ -package com.baeldung.demo.boottest; +package com.baeldung.boot.testing; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties similarity index 100% rename from spring-boot-modules/spring-boot/src/test/resources/application-integrationtest.properties rename to spring-boot-modules/spring-boot-testing/src/test/resources/application-integrationtest.properties diff --git a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties index 0c5b0e13e6..1810c7b1eb 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-testing/src/test/resources/application.properties @@ -3,4 +3,6 @@ spring.redis.host= localhost spring.redis.port= 6370 # security spring.security.user.name=john -spring.security.user.password=123 \ No newline at end of file +spring.security.user.password=123 + +spring.main.allow-bean-definition-overriding=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/README.MD b/spring-boot-modules/spring-boot/README.md similarity index 62% rename from spring-boot-modules/spring-boot/README.MD rename to spring-boot-modules/spring-boot/README.md index c95fe51842..5a45502fd8 100644 --- a/spring-boot-modules/spring-boot/README.MD +++ b/spring-boot-modules/spring-boot/README.md @@ -8,18 +8,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles: - [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) -- [The @ServletComponentScan Annotation in Spring Boot](https://www.baeldung.com/spring-servletcomponentscan) - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) -- [Guide to Internationalization in Spring Boot](https://www.baeldung.com/spring-boot-internationalization) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) -- [Custom Information in Spring Boot Info Endpoint](https://www.baeldung.com/spring-boot-info-actuator-custom) -- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) -- [How to Get All Spring-Managed Beans?](https://www.baeldung.com/spring-show-all-beans) -- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz) -- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) -- [An Introduction to Kong](https://www.baeldung.com/kong) - [Spring Boot: Configuring a Main Class](https://www.baeldung.com/spring-boot-main-class) - [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) diff --git a/spring-boot-modules/spring-boot/pom.xml b/spring-boot-modules/spring-boot/pom.xml index e1299a6a16..5efcffdf03 100644 --- a/spring-boot-modules/spring-boot/pom.xml +++ b/spring-boot-modules/spring-boot/pom.xml @@ -44,22 +44,6 @@ spring-boot-starter-actuator - - com.graphql-java - graphql-spring-boot-starter - ${graphql-spring-boot-starter.version} - - - com.graphql-java - graphql-java-tools - ${graphql-java-tools.version} - - - com.graphql-java - graphiql-spring-boot-starter - ${graphiql-spring-boot-starter.version} - - org.springframework.boot spring-boot-starter-tomcat @@ -104,18 +88,6 @@ provided - - org.togglz - togglz-spring-boot-starter - ${togglz.version} - - - - org.togglz - togglz-spring-security - ${togglz.version} - - org.apache.activemq artemis-server @@ -204,11 +176,7 @@ com.baeldung.intro.App 8.5.11 - 2.4.1.Final 1.9.0 - 5.0.2 - 5.0.2 - 5.2.4 18.0 @ diff --git a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java index eb091b4695..d2bb217c2f 100644 --- a/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java +++ b/spring-boot-modules/spring-boot/src/main/java/com/baeldung/demo/DemoApplication.java @@ -1,13 +1,9 @@ package com.baeldung.demo; -import com.baeldung.graphql.GraphqlConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Import; - @SpringBootApplication -@Import(GraphqlConfiguration.class) public class DemoApplication { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-boot/src/main/resources/application.properties b/spring-boot-modules/spring-boot/src/main/resources/application.properties index 44649fc1c0..142e6c8e6f 100644 --- a/spring-boot-modules/spring-boot/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot/src/main/resources/application.properties @@ -21,12 +21,6 @@ spring.jmx.enabled=true ## for pretty printing of json when endpoints accessed over HTTP http.mappers.jsonPrettyPrint=true -## Configuring info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application G1 -info.app.version=1.0.0 -info.java-vendor = ${java.specification.vendor} - logging.level.org.springframework=INFO #Servlet Configuration diff --git a/spring-boot-modules/spring-boot/src/main/resources/messages.properties b/spring-boot-modules/spring-boot/src/main/resources/messages.properties deleted file mode 100644 index e4dbc44c3f..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/messages.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Hello! Welcome to our website! -lang.change=Change the language -lang.eng=English -lang.fr=French \ No newline at end of file diff --git a/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties b/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties deleted file mode 100644 index ac5853717d..0000000000 --- a/spring-boot-modules/spring-boot/src/main/resources/messages_fr.properties +++ /dev/null @@ -1,4 +0,0 @@ -greeting=Bonjour! Bienvenue sur notre site! -lang.change=Changez la langue -lang.eng=Anglais -lang.fr=Francais \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/pom.xml b/spring-cloud/spring-cloud-ribbon-retry/pom.xml index 5318ea6913..27037d6710 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/pom.xml +++ b/spring-cloud/spring-cloud-ribbon-retry/pom.xml @@ -33,8 +33,20 @@ + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + 0 + + + + + Hoxton.SR3 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java index 0f0a1c4255..decb77e7b9 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetryFailureIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.spring.cloud.ribbon.retry; +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -24,6 +25,7 @@ public class RibbonRetryFailureIntegrationTest { @BeforeAll public static void setup() { + TomcatURLStreamHandlerFactory.disable(); weatherServiceInstance1 = startApp(8021); weatherServiceInstance2 = startApp(8022); } diff --git a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java index 6fdad0f2a9..dc50fe76e6 100644 --- a/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java +++ b/spring-cloud/spring-cloud-ribbon-retry/ribbon-client-service/src/test/java/com/baeldung/spring/cloud/ribbon/retry/RibbonRetrySuccessIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.spring.cloud.ribbon.retry; +import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -25,6 +26,7 @@ public class RibbonRetrySuccessIntegrationTest { @BeforeAll public static void setup() { + TomcatURLStreamHandlerFactory.disable(); weatherServiceInstance1 = startApp(8021); weatherServiceInstance2 = startApp(8022); } diff --git a/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul-fallback/api-gateway/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties new file mode 100644 index 0000000000..640fb2c6a4 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/application.properties @@ -0,0 +1 @@ +logging.level.root=ERROR \ No newline at end of file diff --git a/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml new file mode 100644 index 0000000000..ab4a5f3a20 --- /dev/null +++ b/spring-cloud/spring-cloud-zuul/spring-zuul-rate-limiting/src/test/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + diff --git a/spring-drools/pom.xml b/spring-drools/pom.xml index 5adef4b2a9..8b105158ec 100644 --- a/spring-drools/pom.xml +++ b/spring-drools/pom.xml @@ -8,8 +8,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 @@ -40,17 +41,40 @@ kie-spring ${drools-version} + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + org.springframework spring-test - ${spring-framework.version} + ${spring.version} test
7.0.0.Final - 4.3.3.RELEASE - \ No newline at end of file diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index 299de584ef..d7f875acd0 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -131,6 +131,12 @@ always + + + java.util.logging.config.file + src/test/resources/logging.properties + +
diff --git a/spring-ejb/ejb-beans/src/test/resources/logging.properties b/spring-ejb/ejb-beans/src/test/resources/logging.properties new file mode 100644 index 0000000000..0a0ecef337 --- /dev/null +++ b/spring-ejb/ejb-beans/src/test/resources/logging.properties @@ -0,0 +1,2 @@ +handlers = java.util.logging.ConsoleHandler +java.util.logging.ConsoleHandler.level = SEVERE \ No newline at end of file diff --git a/spring-groovy/.gitignore b/spring-groovy/.gitignore deleted file mode 100644 index c17c227305..0000000000 --- a/spring-groovy/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -/target/ -/project/ -.classpath -.settings -.eclipse -.idea -.project diff --git a/spring-groovy/README.md b/spring-groovy/README.md deleted file mode 100644 index c3bb5636ba..0000000000 --- a/spring-groovy/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Spring Groovy - -This module contains articles about Spring with Groovy - -## Relevant Articles: - -- [Groovy Bean Definitions](https://www.baeldung.com/spring-groovy-beans) diff --git a/spring-groovy/pom.xml b/spring-groovy/pom.xml deleted file mode 100644 index ef5613adf6..0000000000 --- a/spring-groovy/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - com.baeldug - spring-groovy - 0.0.1-SNAPSHOT - spring-groovy - jar - http://maven.apache.org - - - com.baeldung - parent-spring-4 - 0.0.1-SNAPSHOT - ../parent-spring-4 - - - - - org.springframework.integration - spring-integration-groovy - ${spring-integration-groovy.version} - - - org.codehaus.groovy - groovy-all - ${groovy-all.version} - - - - - - - maven-compiler-plugin - ${maven-compiler-plugin.version} - - groovy-eclipse-compiler - true - ${java.version} - ${java.version} - ${project.build.sourceEncoding} - - - - org.codehaus.groovy - groovy-eclipse-compiler - ${groovy-eclipse-compiler.version} - - - org.codehaus.groovy - groovy-eclipse-batch - ${groovy-eclipse-batch.version} - - - - - - - - 2.9.2-01 - 2.4.3-01 - 4.3.7.RELEASE - 2.4.12 - - - diff --git a/spring-jooq/pom.xml b/spring-jooq/pom.xml index c07d6278cb..95418645fa 100644 --- a/spring-jooq/pom.xml +++ b/spring-jooq/pom.xml @@ -30,6 +30,7 @@ org.jooq jooq + ${org.jooq.version} @@ -201,7 +202,7 @@ - 3.11.7 + 3.12.4 1.0.0 1.5 1.0.0 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 3aeaa973af..674d9a2a14 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-katharsis/src/main/java/com/baeldung/Application.java b/spring-katharsis/src/main/java/com/baeldung/Application.java index 6c4f047b26..738afa039e 100644 --- a/spring-katharsis/src/main/java/com/baeldung/Application.java +++ b/spring-katharsis/src/main/java/com/baeldung/Application.java @@ -4,7 +4,7 @@ import io.katharsis.spring.boot.v3.KatharsisConfigV3; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Import; @SpringBootApplication diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java index c5e6326075..a249def128 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/RoleResourceRepository.java @@ -7,6 +7,9 @@ import io.katharsis.repository.ResourceRepositoryV2; import io.katharsis.resource.list.ResourceList; import com.baeldung.persistence.model.Role; + +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,7 +20,8 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public Role findOne(Long id, QuerySpec querySpec) { - return roleRepository.findOne(id); + Optional role = roleRepository.findById(id); + return role.isPresent()? role.get() : null; } @Override @@ -27,7 +31,7 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public ResourceList findAll(Iterable ids, QuerySpec querySpec) { - return querySpec.apply(roleRepository.findAll(ids)); + return querySpec.apply(roleRepository.findAllById(ids)); } @Override @@ -37,7 +41,7 @@ public class RoleResourceRepository implements ResourceRepositoryV2 @Override public void delete(Long id) { - roleRepository.delete(id); + roleRepository.deleteById(id); } @Override diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java index 616431f3f0..af71da4727 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserResourceRepository.java @@ -6,6 +6,8 @@ import io.katharsis.queryspec.QuerySpec; import io.katharsis.repository.ResourceRepositoryV2; import io.katharsis.resource.list.ResourceList; +import java.util.Optional; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -17,7 +19,8 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public User findOne(Long id, QuerySpec querySpec) { - return userRepository.findOne(id); + Optional user = userRepository.findById(id); + return user.isPresent()? user.get() : null; } @Override @@ -27,7 +30,7 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public ResourceList findAll(Iterable ids, QuerySpec querySpec) { - return querySpec.apply(userRepository.findAll(ids)); + return querySpec.apply(userRepository.findAllById(ids)); } @Override @@ -37,7 +40,7 @@ public class UserResourceRepository implements ResourceRepositoryV2 @Override public void delete(Long id) { - userRepository.delete(id); + userRepository.deleteById(id); } @Override diff --git a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java index 066292c00f..d0b4a464c9 100644 --- a/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java +++ b/spring-katharsis/src/main/java/com/baeldung/persistence/katharsis/UserToRoleRelationshipRepository.java @@ -8,6 +8,7 @@ import io.katharsis.repository.RelationshipRepositoryV2; import io.katharsis.resource.list.ResourceList; import java.util.HashSet; +import java.util.Optional; import java.util.Set; import com.baeldung.persistence.model.Role; @@ -31,7 +32,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void setRelations(User user, Iterable roleIds, String fieldName) { final Set roles = new HashSet(); - roles.addAll(roleRepository.findAll(roleIds)); + roles.addAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -39,7 +40,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void addRelations(User user, Iterable roleIds, String fieldName) { final Set roles = user.getRoles(); - roles.addAll(roleRepository.findAll(roleIds)); + roles.addAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -47,7 +48,7 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public void removeRelations(User user, Iterable roleIds, String fieldName) { final Set roles = user.getRoles(); - roles.removeAll(roleRepository.findAll(roleIds)); + roles.removeAll(roleRepository.findAllById(roleIds)); user.setRoles(roles); userRepository.save(user); } @@ -60,7 +61,8 @@ public class UserToRoleRelationshipRepository implements RelationshipRepositoryV @Override public ResourceList findManyTargets(Long sourceId, String fieldName, QuerySpec querySpec) { - final User user = userRepository.findOne(sourceId); + final Optional userOptional = userRepository.findById(sourceId); + User user = userOptional.isPresent() ? userOptional.get() : new User(); return querySpec.apply(user.getRoles()); } diff --git a/spring-katharsis/src/main/resources/application.properties b/spring-katharsis/src/main/resources/application.properties index 120b3c62ee..415ec1723b 100644 --- a/spring-katharsis/src/main/resources/application.properties +++ b/spring-katharsis/src/main/resources/application.properties @@ -6,7 +6,7 @@ spring.jpa.hibernate.ddl-auto = create-drop spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect server.port=8082 -server.context-path=/spring-katharsis +server.servlet.context-path=/spring-katharsis katharsis.domainName=http://localhost:8082/spring-katharsis katharsis.pathPrefix=/ \ No newline at end of file diff --git a/spring-remoting/remoting-hessian-burlap/pom.xml b/spring-remoting/remoting-hessian-burlap/pom.xml index fac6e1cb2e..67e3e3eab4 100644 --- a/spring-remoting/remoting-hessian-burlap/pom.xml +++ b/spring-remoting/remoting-hessian-burlap/pom.xml @@ -9,6 +9,7 @@ pom + com.baeldung parent-boot-1 0.0.1-SNAPSHOT diff --git a/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml new file mode 100644 index 0000000000..7ee581d3d8 --- /dev/null +++ b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-format.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.1 +info: + title: API Title + description: This is a sample API. + version: 1.0.0 +servers: + - url: https://host/ +paths: + /users: + get: + summary: Get Users + operationId: getUsers + responses: + 200: + description: Valid input + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + createdAt: + type: string + format: date + description: Creation date + example: "2021-01-30" + username: + type: string \ No newline at end of file diff --git a/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml new file mode 100644 index 0000000000..ffba36f3da --- /dev/null +++ b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-date-pattern.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.1 +info: + title: API Title + description: This is a sample API. + version: 1.0.0 +servers: + - url: https://host/ +paths: + /users: + get: + summary: Get Users + operationId: getUsers + responses: + 200: + description: Valid input + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + customDate: + type: string + pattern: '^\d{4}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$' + description: Custom date + example: "20210130" + username: + type: string \ No newline at end of file diff --git a/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml new file mode 100644 index 0000000000..8bf4ddd2dc --- /dev/null +++ b/spring-rest-http/src/main/resources/openapi-dates-definitions/openapi-3-datetime-format.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.1 +info: + title: API Title + description: This is a sample API. + version: 1.0.0 +servers: + - url: https://host/ +paths: + /users: + get: + summary: Get Users + operationId: getUsers + responses: + 200: + description: Valid input + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' +components: + schemas: + User: + type: object + properties: + id: + type: integer + format: int64 + createdAt: + type: string + format: date-time + description: Creation date and time + example: "2021-01-30T08:30:00Z" + username: + type: string \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-digest-auth/pom.xml b/spring-security-modules/spring-security-web-digest-auth/pom.xml index 2579a11f97..39433c1295 100644 --- a/spring-security-modules/spring-security-web-digest-auth/pom.xml +++ b/spring-security-modules/spring-security-web-digest-auth/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring-4 + parent-spring-5 0.0.1-SNAPSHOT - ../../parent-spring-4 + ../../parent-spring-5 diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java new file mode 100644 index 0000000000..dfcfdc1117 --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogController.java @@ -0,0 +1,23 @@ +package com.baeldung.thymeleaf.blog; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import java.util.Random; + +@Controller +public class BlogController { + + @GetMapping("/blog/new") + public String newBlogPost(Model model) { + // Set a random ID so we can see it in the HTML form + BlogDTO blog = new BlogDTO(); + blog.setBlogId(Math.abs(new Random().nextLong() % 1000000)); + + model.addAttribute("blog", blog); + + return "blog/blog-new"; + } + +} diff --git a/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java new file mode 100644 index 0000000000..44c77be5ce --- /dev/null +++ b/spring-thymeleaf-3/src/main/java/com/baeldung/thymeleaf/blog/BlogDTO.java @@ -0,0 +1,66 @@ +package com.baeldung.thymeleaf.blog; + +import java.util.Date; + +public class BlogDTO { + + private long blogId; + + private String title; + + private String body; + + private String author; + + private String category; + + private Date publishedDate; + + public long getBlogId() { + return blogId; + } + + public void setBlogId(long blogId) { + this.blogId = blogId; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getBody() { + return body; + } + + public void setBody(String body) { + this.body = body; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Date getPublishedDate() { + return publishedDate; + } + + public void setPublishedDate(Date publishedDate) { + this.publishedDate = publishedDate; + } +} diff --git a/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html b/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html new file mode 100644 index 0000000000..10747b4b07 --- /dev/null +++ b/spring-thymeleaf-3/src/main/resources/templates/blog/blog-new.html @@ -0,0 +1,36 @@ + + + + + Hidden Input Examples + + + +

Hidden Input Example 1

+
+ + + + + +
+ +

Hidden Input Example 2

+
+ + + + + +
+ +

Hidden Input Example 3

+
+ + + + + +
+ + \ No newline at end of file diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java new file mode 100644 index 0000000000..4bbd2843f2 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/Employee.java @@ -0,0 +1,11 @@ +package com.baeldung.mockito.whenvsdomethods; + +import java.time.DayOfWeek; + +public interface Employee { + + String greet(); + + void work(DayOfWeek day); + +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java new file mode 100644 index 0000000000..24276ba958 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/mockito/whenvsdomethods/IAmOnHolidayException.java @@ -0,0 +1,5 @@ +package com.baeldung.mockito.whenvsdomethods; + +public class IAmOnHolidayException extends RuntimeException { + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java new file mode 100644 index 0000000000..8c2b86daf1 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/mockito/whenvsdomethods/WhenVsDoMethodsUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.mockito.whenvsdomethods; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + +import java.time.DayOfWeek; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class WhenVsDoMethodsUnitTest { + + @Mock + private Employee employee; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + void givenNonVoidMethod_callingWhen_shouldConfigureBehavior() { + // given + when(employee.greet()).thenReturn("Hello"); + + // when + String greeting = employee.greet(); + + // then + assertThat(greeting, is("Hello")); + } + + @Test + void givenNonVoidMethod_callingDoReturn_shouldConfigureBehavior() { + // given + doReturn("Hello").when(employee).greet(); + + // when + String greeting = employee.greet(); + + // then + assertThat(greeting, is("Hello")); + } + + @Test + void givenVoidMethod_callingDoThrow_shouldConfigureBehavior() { + // given + doThrow(new IAmOnHolidayException()).when(employee).work(DayOfWeek.SUNDAY); + + // when + Executable workCall = () -> employee.work(DayOfWeek.SUNDAY); + + // then + assertThrows(IAmOnHolidayException.class, workCall); + } + + @Test + void givenNonVoidMethod_callingGiven_shouldConfigureBehavior() { + // given + given(employee.greet()).willReturn("Hello"); + + // when + String greeting = employee.greet(); + + // then + assertThat(greeting, is("Hello")); + } + + @Test + void givenVoidMethod_callingWillThrow_shouldConfigureBehavior() { + // given + willThrow(new IAmOnHolidayException()).given(employee).work(DayOfWeek.SUNDAY); + + // when + Executable workCall = () -> employee.work(DayOfWeek.SUNDAY); + + // then + assertThrows(IAmOnHolidayException.class, workCall); + } + +} diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index b467b3c503..f1d30cd7a1 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -31,7 +31,8 @@ rest-assured rest-testing selenium-junit-testng - spring-testing + spring-testing + spring-testing-2 test-containers testing-assertions testng diff --git a/testing-modules/spring-testing-2/.gitignore b/testing-modules/spring-testing-2/.gitignore new file mode 100644 index 0000000000..ffc5bf3bad --- /dev/null +++ b/testing-modules/spring-testing-2/.gitignore @@ -0,0 +1,3 @@ +.idea/** +target/** +*.iml \ No newline at end of file diff --git a/testing-modules/spring-testing-2/README.md b/testing-modules/spring-testing-2/README.md new file mode 100644 index 0000000000..729105e3fd --- /dev/null +++ b/testing-modules/spring-testing-2/README.md @@ -0,0 +1 @@ +## Relevant Articles: diff --git a/testing-modules/spring-testing-2/pom.xml b/testing-modules/spring-testing-2/pom.xml new file mode 100644 index 0000000000..c7ca2804fb --- /dev/null +++ b/testing-modules/spring-testing-2/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + spring-testing-2 + 0.1-SNAPSHOT + spring-testing-2 + + + 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.postgresql + postgresql + runtime + + + + + org.testcontainers + postgresql + ${testcontainers.version} + test + + + org.testcontainers + junit-jupiter + ${testcontainers.version} + test + + + + + + 2.1.9.RELEASE + 2.1.9.RELEASE + 1.12.2 + + \ No newline at end of file diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java new file mode 100644 index 0000000000..6b6bfb7bd6 --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/Article.java @@ -0,0 +1,45 @@ +package com.baeldung.dynamicproperties; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +import static javax.persistence.GenerationType.IDENTITY; + +@Entity +@Table(name = "articles") +public class Article { + + @Id + @GeneratedValue(strategy = IDENTITY) + private Long id; + + private String title; + + private String content; + + 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 getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } +} diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java new file mode 100644 index 0000000000..3f3731f6dc --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/ArticleRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.dynamicproperties; + +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ArticleRepository extends JpaRepository { +} diff --git a/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java new file mode 100644 index 0000000000..d64bd965fc --- /dev/null +++ b/testing-modules/spring-testing-2/src/main/java/com/baeldung/dynamicproperties/DynamicPropertiesApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.dynamicproperties; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DynamicPropertiesApplication { + + public static void main(String[] args) { + SpringApplication.run(DynamicPropertiesApplication.class, args); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java new file mode 100644 index 0000000000..74c31229bd --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +@ActiveProfiles("pg") +public class ArticleLiveTest { + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + @Autowired + private ArticleRepository articleRepository; + + @DynamicPropertySource + static void registerPgProperties(DynamicPropertyRegistry registry) { + registry.add("spring.datasource.url", + () -> String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort())); + registry.add("spring.datasource.username", () -> "postgres"); + registry.add("spring.datasource.password", () -> "pass"); + } + + @Test + void givenAnArticle_whenPersisted_thenCanBeFoundInTheDb() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java new file mode 100644 index 0000000000..bb3ad28365 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTestFixtureLiveTest.java @@ -0,0 +1,31 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@ActiveProfiles("pg") +@ExtendWith(PostgreSQLExtension.class) +public class ArticleTestFixtureLiveTest { + + @Autowired + private ArticleRepository articleRepository; + + @Test + void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java new file mode 100644 index 0000000000..87234505a9 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/ArticleTraditionalLiveTest.java @@ -0,0 +1,57 @@ +package com.baeldung.dynamicproperties; + +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.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.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Testcontainers +@ActiveProfiles("pg") +@ContextConfiguration(initializers = ArticleTraditionalLiveTest.EnvInitializer.class) +class ArticleTraditionalLiveTest { + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + static class EnvInitializer implements ApplicationContextInitializer { + + @Override + public void initialize(ConfigurableApplicationContext applicationContext) { + TestPropertyValues.of( + String.format("spring.datasource.url=jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()), + "spring.datasource.username=postgres", + "spring.datasource.password=pass" + ).applyTo(applicationContext); + } + } + + @Autowired + private ArticleRepository articleRepository; + + @Test + void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() { + Article article = new Article(); + article.setTitle("A Guide to @DynamicPropertySource in Spring"); + article.setContent("Today's applications..."); + + articleRepository.save(article); + Article persisted = articleRepository.findAll().get(0); + assertThat(persisted.getId()).isNotNull(); + assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring"); + assertThat(persisted.getContent()).isEqualTo("Today's applications..."); + } +} diff --git a/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java new file mode 100644 index 0000000000..8c08ad67d7 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/java/com/baeldung/dynamicproperties/PostgreSQLExtension.java @@ -0,0 +1,31 @@ +package com.baeldung.dynamicproperties; + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.testcontainers.containers.PostgreSQLContainer; + +public class PostgreSQLExtension implements BeforeAllCallback, AfterAllCallback { + + private PostgreSQLContainer postgres; + + @Override + public void beforeAll(ExtensionContext context) { + postgres = new PostgreSQLContainer<>("postgres:11") + .withDatabaseName("prop") + .withUsername("postgres") + .withPassword("pass") + .withExposedPorts(5432); + + postgres.start(); + String jdbcUrl = String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()); + System.setProperty("spring.datasource.url", jdbcUrl); + System.setProperty("spring.datasource.username", "postgres"); + System.setProperty("spring.datasource.password", "pass"); + } + + @Override + public void afterAll(ExtensionContext context) { + postgres.stop(); + } +} diff --git a/testing-modules/spring-testing-2/src/test/resources/application-pg.properties b/testing-modules/spring-testing-2/src/test/resources/application-pg.properties new file mode 100644 index 0000000000..cb7bff1889 --- /dev/null +++ b/testing-modules/spring-testing-2/src/test/resources/application-pg.properties @@ -0,0 +1,2 @@ +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=create-drop \ No newline at end of file diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 0a7c4b0860..fa0f666c7f 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -18,11 +18,45 @@ logback-classic 1.2.3 + + org.junit.jupiter + junit-jupiter-engine + 5.6.2 + test + + + org.junit.jupiter + junit-jupiter-api + 5.6.2 + test + org.assertj assertj-core - 3.15.0 + 3.16.1 + test + + + org.hamcrest + hamcrest-all + 1.3 + test + + + org.apache.commons + commons-collections4 + 4.4 test
+ + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.1 + + + diff --git a/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java new file mode 100644 index 0000000000..bf278cea90 --- /dev/null +++ b/testing-modules/testing-assertions/src/test/java/com/baeldung/listassert/OrderAgnosticListComparisonUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.listassert; + +import org.apache.commons.collections4.CollectionUtils; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class OrderAgnosticListComparisonUnitTest { + + private final List first = Arrays.asList(1, 3, 4, 6, 8); + private final List second = Arrays.asList(8, 1, 6, 3, 4); + private final List third = Arrays.asList(1, 3, 3, 6, 6); + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrue() { + assertTrue(first.size() == second.size() && first.containsAll(second) && second.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeFalse() { + assertFalse(first.size() == third.size() && first.containsAll(third) && third.containsAll(first)); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() { + MatcherAssert.assertThat(first, Matchers.containsInAnyOrder(second.toArray())); + } + + @Test + public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() { + assertTrue(CollectionUtils.isEqualCollection(first, second)); + assertFalse(CollectionUtils.isEqualCollection(first, third)); + } + + @Test + void whenTestingForOrderAgnosticEqualityBothList_ShouldBeEqual() { + assertThat(first).hasSameElementsAs(second); + } + + @Test + void whenTestingForOrderAgnosticEqualityBothList_ShouldNotBeEqual() { + List a = Arrays.asList("a", "a", "b", "c"); + List b = Arrays.asList("a", "b", "c"); + + assertThat(a).hasSameElementsAs(b); + } +}