commit
fad1cb28da
|
@ -88,3 +88,6 @@ apache-cxf/cxf-aegis/baeldung.xml
|
||||||
testing-modules/report-*.json
|
testing-modules/report-*.json
|
||||||
|
|
||||||
libraries-2/*.db
|
libraries-2/*.db
|
||||||
|
|
||||||
|
# SDKMan
|
||||||
|
.sdkmanrc
|
||||||
|
|
|
@ -74,6 +74,7 @@
|
||||||
<plugins>
|
<plugins>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
<version>3.3.0</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<phase>package</phase>
|
<phase>package</phase>
|
||||||
|
|
|
@ -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)
|
||||||
|
|
|
@ -0,0 +1,48 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project
|
||||||
|
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
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">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-java-11-2</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
<name>core-java-11-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
<relativePath>../..</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>${maven-compiler-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<source>${maven.compiler.source.version}</source>
|
||||||
|
<target>${maven.compiler.target.version}</target>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<maven.compiler.source.version>11</maven.compiler.source.version>
|
||||||
|
<maven.compiler.target.version>11</maven.compiler.target.version>
|
||||||
|
<assertj.version>3.17.2</assertj.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -7,7 +7,9 @@ import java.util.Optional;
|
||||||
import java.util.function.Supplier;
|
import java.util.function.Supplier;
|
||||||
import java.util.stream.Stream;
|
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 {
|
public class OptionalChainingUnitTest {
|
||||||
|
|
|
@ -9,7 +9,9 @@ import java.util.List;
|
||||||
import java.util.NoSuchElementException;
|
import java.util.NoSuchElementException;
|
||||||
import java.util.Optional;
|
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 {
|
public class OptionalUnitTest {
|
||||||
|
|
||||||
|
@ -262,6 +264,12 @@ public class OptionalUnitTest {
|
||||||
.orElseThrow(IllegalArgumentException::new);
|
.orElseThrow(IllegalArgumentException::new);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test(expected = NoSuchElementException.class)
|
||||||
|
public void whenNoArgOrElseThrowWorks_thenCorrect() {
|
||||||
|
String nullName = null;
|
||||||
|
String name = Optional.ofNullable(nullName).orElseThrow();
|
||||||
|
}
|
||||||
|
|
||||||
public String getMyDefault() {
|
public String getMyDefault() {
|
||||||
LOG.debug("Getting default value...");
|
LOG.debug("Getting default value...");
|
||||||
return "Default Value";
|
return "Default Value";
|
|
@ -107,7 +107,7 @@
|
||||||
<uberjar.name>benchmarks</uberjar.name>
|
<uberjar.name>benchmarks</uberjar.name>
|
||||||
<jmh.version>1.22</jmh.version>
|
<jmh.version>1.22</jmh.version>
|
||||||
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
<eclipse.collections.version>10.0.0</eclipse.collections.version>
|
||||||
<shade.plugin.version>10.0.0</shade.plugin.version>
|
<shade.plugin.version>3.2.4</shade.plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="WARN">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
|
@ -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<Set<PosixFilePermission>> 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();
|
||||||
|
}
|
||||||
|
}
|
|
@ -4,7 +4,6 @@ This module contains articles about Java Optional.
|
||||||
|
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- [Java Optional as Return Type](https://www.baeldung.com/java-optional-return)
|
- [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)
|
- [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)
|
- [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)
|
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
||||||
|
|
|
@ -0,0 +1,7 @@
|
||||||
|
## Core Kotlin Collections
|
||||||
|
|
||||||
|
This module contains articles about core Kotlin collections.
|
||||||
|
|
||||||
|
### Relevant articles:
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,47 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
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">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<artifactId>core-kotlin-collections-2</artifactId>
|
||||||
|
<name>core-kotlin-collections-2</name>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||||
|
<artifactId>core-kotlin-modules</artifactId>
|
||||||
|
<version>1.0.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
|
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||||
|
<version>${kotlin.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-math3</artifactId>
|
||||||
|
<version>${commons-math3.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.assertj</groupId>
|
||||||
|
<artifactId>assertj-core</artifactId>
|
||||||
|
<version>${assertj.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.jetbrains.kotlin</groupId>
|
||||||
|
<artifactId>kotlin-test</artifactId>
|
||||||
|
<version>${kotlin.version}</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<kotlin.version>1.3.30</kotlin.version>
|
||||||
|
<commons-math3.version>3.6.1</commons-math3.version>
|
||||||
|
<assertj.version>3.10.0</assertj.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
</project>
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
|
@ -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())
|
||||||
|
}
|
||||||
|
}
|
|
@ -22,6 +22,30 @@ fun main() {
|
||||||
numbers.each { println(random * it) } // capturing the random variable
|
numbers.each { println(random * it) } // capturing the random variable
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun namedFunction(): Int {
|
||||||
|
return 42
|
||||||
|
}
|
||||||
|
|
||||||
|
fun anonymous(): () -> Int {
|
||||||
|
return fun(): Int {
|
||||||
|
return 42
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <T> List<T>.eachIndexed(f: (Int, T) -> Unit) {
|
||||||
|
for (i in indices) {
|
||||||
|
f(i, this[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun <T> List<T>.indexOf(x: T): Int {
|
||||||
|
eachIndexed { index, value ->
|
||||||
|
if (value == x) return index
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a random number.
|
* Generates a random number.
|
||||||
*/
|
*/
|
||||||
|
|
|
@ -21,6 +21,7 @@
|
||||||
<module>core-kotlin-advanced</module>
|
<module>core-kotlin-advanced</module>
|
||||||
<module>core-kotlin-annotations</module>
|
<module>core-kotlin-annotations</module>
|
||||||
<module>core-kotlin-collections</module>
|
<module>core-kotlin-collections</module>
|
||||||
|
<module>core-kotlin-collections-2</module>
|
||||||
<module>core-kotlin-concurrency</module>
|
<module>core-kotlin-concurrency</module>
|
||||||
<module>core-kotlin-date-time</module>
|
<module>core-kotlin-date-time</module>
|
||||||
<module>core-kotlin-design-patterns</module>
|
<module>core-kotlin-design-patterns</module>
|
||||||
|
|
|
@ -6,3 +6,4 @@ This module contains articles about Drools
|
||||||
|
|
||||||
- [Introduction to Drools](https://www.baeldung.com/drools)
|
- [Introduction to Drools](https://www.baeldung.com/drools)
|
||||||
- [An Example of Backward Chaining in Drools](https://www.baeldung.com/drools-backward-chaining)
|
- [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)
|
||||||
|
|
|
@ -1,21 +1,24 @@
|
||||||
package com.baeldung.arrayconversion;
|
package com.baeldung.arrayconversion;
|
||||||
|
|
||||||
|
import org.hamcrest.CoreMatchers;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
import static org.junit.Assert.assertArrayEquals;
|
||||||
|
|
||||||
public class ArrayToListConversionUnitTest {
|
public class ArrayToListConversionUnitTest {
|
||||||
|
|
||||||
@Test(expected = UnsupportedOperationException.class)
|
@Test(expected = UnsupportedOperationException.class)
|
||||||
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
|
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
|
||||||
String[] stringArray = new String[] { "A", "B", "C", "D" };
|
String[] stringArray = new String[] { "A", "B", "C", "D" };
|
||||||
List<String> stringList = Arrays.asList(stringArray);
|
List<String> stringList = Arrays.asList(stringArray);
|
||||||
System.out.println(stringList);
|
|
||||||
stringList.set(0, "E");
|
stringList.set(0, "E");
|
||||||
System.out.println(stringList);
|
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D"));
|
||||||
System.out.println(Arrays.toString(stringArray));
|
assertArrayEquals(stringArray, new String[] { "E", "B", "C", "D" });
|
||||||
stringList.add("F");
|
stringList.add("F");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -23,10 +26,10 @@ public class ArrayToListConversionUnitTest {
|
||||||
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
|
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
|
||||||
String[] stringArray = new String[] { "A", "B", "C", "D" };
|
String[] stringArray = new String[] { "A", "B", "C", "D" };
|
||||||
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
|
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
|
||||||
System.out.println(stringList);
|
|
||||||
stringList.set(0, "E");
|
stringList.set(0, "E");
|
||||||
System.out.println(stringList);
|
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D"));
|
||||||
System.out.println(Arrays.toString(stringArray));
|
assertArrayEquals(stringArray, new String[] { "A", "B", "C", "D" });
|
||||||
stringList.add("F");
|
stringList.add("F");
|
||||||
|
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D", "F"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -237,6 +237,26 @@
|
||||||
<build>
|
<build>
|
||||||
<defaultGoal>spring-boot:run</defaultGoal>
|
<defaultGoal>spring-boot:run</defaultGoal>
|
||||||
<plugins>
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.codehaus.mojo</groupId>
|
||||||
|
<artifactId>properties-maven-plugin</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<goals>
|
||||||
|
<goal>set-system-properties</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<properties>
|
||||||
|
<property>
|
||||||
|
<name>org.slf4j.simpleLogger.log.com.github.eirslett</name>
|
||||||
|
<value>error</value>
|
||||||
|
</property>
|
||||||
|
</properties>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
|
|
@ -9,6 +9,8 @@
|
||||||
<packaging>pom</packaging>
|
<packaging>pom</packaging>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
<!-- Jhipster project is autogenerated and upgrading it will need a newly generated project.
|
||||||
|
Also, we already have jhipster-5 which has new version of boot-2. So, this project should be left as a legacy version. -->
|
||||||
<artifactId>parent-boot-1</artifactId>
|
<artifactId>parent-boot-1</artifactId>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
|
@ -14,29 +14,24 @@
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.security.oauth</groupId>
|
<groupId>org.springframework.security.oauth</groupId>
|
||||||
<artifactId>spring-security-oauth2</artifactId>
|
<artifactId>spring-security-oauth2</artifactId>
|
||||||
<version>${spring-boot.version}</version>
|
<version>${spring-boot.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-web</artifactId>
|
<artifactId>spring-web</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.github.scribejava</groupId>
|
<groupId>com.github.scribejava</groupId>
|
||||||
<artifactId>scribejava-apis</artifactId>
|
<artifactId>scribejava-apis</artifactId>
|
||||||
<version>${scribejava.version}</version>
|
<version>${scribejava.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.google.crypto.tink</groupId>
|
<groupId>com.google.crypto.tink</groupId>
|
||||||
<artifactId>tink</artifactId>
|
<artifactId>tink</artifactId>
|
||||||
|
@ -72,6 +67,16 @@
|
||||||
<artifactId>jasypt</artifactId>
|
<artifactId>jasypt</artifactId>
|
||||||
<version>${jasypt.version}</version>
|
<version>${jasypt.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.jcraft</groupId>
|
||||||
|
<artifactId>jsch</artifactId>
|
||||||
|
<version>${jsch.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.sshd</groupId>
|
||||||
|
<artifactId>sshd-core</artifactId>
|
||||||
|
<version>${apache-mina.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
@ -81,6 +86,8 @@
|
||||||
<cryptacular.version>1.2.2</cryptacular.version>
|
<cryptacular.version>1.2.2</cryptacular.version>
|
||||||
<jasypt.version>1.9.2</jasypt.version>
|
<jasypt.version>1.9.2</jasypt.version>
|
||||||
<bouncycastle.version>1.58</bouncycastle.version>
|
<bouncycastle.version>1.58</bouncycastle.version>
|
||||||
|
<jsch.version>0.1.55</jsch.version>
|
||||||
|
<apache-mina.version>2.5.1</apache-mina.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,8 +1,6 @@
|
||||||
### Relevant Articles:
|
### Relevant Articles:
|
||||||
- TBD
|
|
||||||
- [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback)
|
- [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)
|
- [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
|
### References
|
||||||
|
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc;
|
||||||
|
|
||||||
import java.sql.*;
|
import java.sql.*;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.joins;
|
package com.baeldung.spring.jdbc.joins;
|
||||||
|
|
||||||
class ArticleWithAuthor {
|
class ArticleWithAuthor {
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.joins;
|
package com.baeldung.spring.jdbc.joins;
|
||||||
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc;
|
||||||
|
|
||||||
|
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc;
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc;
|
||||||
|
|
||||||
import org.apache.log4j.Logger;
|
import org.apache.log4j.Logger;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.joins;
|
package com.baeldung.spring.jdbc.joins;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
|
@ -0,0 +1,6 @@
|
||||||
|
create table book (
|
||||||
|
id numeric,
|
||||||
|
title varchar(128),
|
||||||
|
author varchar(256),
|
||||||
|
constraint pk_book primary key (id)
|
||||||
|
);
|
|
@ -0,0 +1 @@
|
||||||
|
drop table book;
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="WARN">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
|
@ -5,6 +5,6 @@ hibernate.connection.autocommit=true
|
||||||
jdbc.password=
|
jdbc.password=
|
||||||
|
|
||||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||||
hibernate.show_sql=true
|
hibernate.show_sql=false
|
||||||
hibernate.hbm2ddl.auto=create-drop
|
hibernate.hbm2ddl.auto=create-drop
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<configuration scan="true" scanPeriod="15 seconds" debug="false">
|
||||||
|
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||||
|
<encoder>
|
||||||
|
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
|
||||||
|
</encoder>
|
||||||
|
</appender>
|
||||||
|
|
||||||
|
<root level="WARN">
|
||||||
|
<appender-ref ref="STDOUT" />
|
||||||
|
</root>
|
||||||
|
</configuration>
|
|
@ -68,7 +68,9 @@
|
||||||
<module>spring-data-jpa-enterprise</module>
|
<module>spring-data-jpa-enterprise</module>
|
||||||
<module>spring-data-jpa-filtering</module>
|
<module>spring-data-jpa-filtering</module>
|
||||||
<module>spring-data-jpa-query</module>
|
<module>spring-data-jpa-query</module>
|
||||||
|
<module>spring-data-jpa-query-2</module>
|
||||||
<module>spring-data-jpa-repo</module>
|
<module>spring-data-jpa-repo</module>
|
||||||
|
<module>spring-data-jpa-repo-2</module>
|
||||||
|
|
||||||
<module>spring-data-jdbc</module>
|
<module>spring-data-jdbc</module>
|
||||||
|
|
||||||
|
@ -82,9 +84,9 @@
|
||||||
<module>spring-hibernate4</module>
|
<module>spring-hibernate4</module>
|
||||||
<module>spring-jpa</module>
|
<module>spring-jpa</module>
|
||||||
<module>spring-jpa-2</module>
|
<module>spring-jpa-2</module>
|
||||||
|
<module>spring-jdbc</module>
|
||||||
<!-- <module>spring-mybatis</module> --> <!-- needs fixing in BAEL-9021 -->
|
<!-- <module>spring-mybatis</module> --> <!-- needs fixing in BAEL-9021 -->
|
||||||
<module>spring-persistence-simple</module>
|
<module>spring-persistence-simple</module>
|
||||||
<module>spring-persistence-simple-2</module>
|
|
||||||
</modules>
|
</modules>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
|
|
|
@ -8,9 +8,9 @@
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-spring-4</artifactId>
|
<artifactId>parent-spring-5</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-spring-4</relativePath>
|
<relativePath>../../parent-spring-5</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -30,6 +30,31 @@
|
||||||
</exclusion>
|
</exclusion>
|
||||||
</exclusions>
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-beans</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-context</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-aop</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-expression</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-tx</artifactId>
|
||||||
|
<version>${spring.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework</groupId>
|
<groupId>org.springframework</groupId>
|
||||||
<artifactId>spring-test</artifactId>
|
<artifactId>spring-test</artifactId>
|
||||||
|
|
|
@ -3,7 +3,9 @@
|
||||||
This module contains articles about querying data using Spring Data JPA
|
This module contains articles about querying data using Spring Data JPA
|
||||||
|
|
||||||
### Relevant Articles:
|
### 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)
|
- [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)
|
- More articles: [[<-- prev]](../spring-data-jpa-query)
|
||||||
|
|
||||||
### Eclipse Config
|
### Eclipse Config
|
||||||
|
|
|
@ -3,7 +3,7 @@
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
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">
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
<modelVersion>4.0.0</modelVersion>
|
<modelVersion>4.0.0</modelVersion>
|
||||||
<artifactId>spring-data-jpa-query</artifactId>
|
<artifactId>spring-data-jpa-query-2</artifactId>
|
||||||
<name>spring-data-jpa-query-2</name>
|
<name>spring-data-jpa-query-2</name>
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.spring.data.persistence.model;
|
package com.baeldung.spring.data.jpa.query;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import javax.persistence.*;
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
@ -8,7 +8,6 @@ import java.util.Objects;
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "users")
|
@Table(name = "users")
|
||||||
public class User {
|
public class User {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private int id;
|
private int id;
|
||||||
|
@ -28,9 +27,6 @@ public class User {
|
||||||
|
|
||||||
private Integer status;
|
private Integer status;
|
||||||
|
|
||||||
@OneToMany
|
|
||||||
List<Possession> possessionList;
|
|
||||||
|
|
||||||
public User() {
|
public User() {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
|
@ -87,12 +83,20 @@ public class User {
|
||||||
return creationDate;
|
return creationDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Possession> getPossessionList() {
|
public LocalDate getLastLoginDate() {
|
||||||
return possessionList;
|
return lastLoginDate;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setPossessionList(List<Possession> possessionList) {
|
public void setLastLoginDate(LocalDate lastLoginDate) {
|
||||||
this.possessionList = possessionList;
|
this.lastLoginDate = lastLoginDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isActive() {
|
||||||
|
return active;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setActive(boolean active) {
|
||||||
|
this.active = active;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -119,21 +123,4 @@ public class User {
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
return Objects.hash(id, name, creationDate, age, email, status);
|
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
|
@ -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.Page;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.domain.Sort;
|
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.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
|
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
|
||||||
|
|
||||||
Stream<User> findAllByName(String name);
|
|
||||||
|
|
||||||
@Query("SELECT u FROM User u WHERE u.status = 1")
|
@Query("SELECT u FROM User u WHERE u.status = 1")
|
||||||
Collection<User> findAllActiveUsers();
|
Collection<User> findAllActiveUsers();
|
||||||
|
|
||||||
@Query("select u from User u where u.email like '%@gmail.com'")
|
|
||||||
List<User> findUsersWithGmailAddress();
|
|
||||||
|
|
||||||
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
|
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
|
||||||
Collection<User> findAllActiveUsersNative();
|
Collection<User> 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")
|
@Query(value = "SELECT u FROM User u")
|
||||||
List<User> findAllUsers(Sort sort);
|
List<User> findAllUsers(Sort sort);
|
||||||
|
|
||||||
|
@ -63,6 +27,27 @@ public interface UserRepository extends JpaRepository<User, Integer>, UserReposi
|
||||||
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
|
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
|
||||||
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
|
Page<User> 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<User> findUserByNameList(@Param("names") Collection<String> names);
|
||||||
|
|
||||||
@Modifying
|
@Modifying
|
||||||
@Query("update User u set u.status = :status where u.name = :name")
|
@Query("update User u set u.status = :status where u.name = :name")
|
||||||
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
|
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
|
||||||
|
@ -74,25 +59,4 @@ public interface UserRepository extends JpaRepository<User, Integer>, UserReposi
|
||||||
@Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
|
@Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
|
||||||
@Modifying
|
@Modifying
|
||||||
void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active);
|
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<User> findUserByNameList(@Param("names") Collection<String> 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();
|
|
||||||
}
|
}
|
|
@ -1,6 +1,4 @@
|
||||||
package com.baeldung.spring.data.persistence.repository;
|
package com.baeldung.spring.data.jpa.query;
|
||||||
|
|
||||||
import com.baeldung.spring.data.persistence.model.User;
|
|
||||||
|
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
|
@ -1,6 +1,4 @@
|
||||||
package com.baeldung.spring.data.persistence.repository;
|
package com.baeldung.spring.data.jpa.query;
|
||||||
|
|
||||||
import com.baeldung.spring.data.persistence.model.User;
|
|
||||||
|
|
||||||
import javax.persistence.EntityManager;
|
import javax.persistence.EntityManager;
|
||||||
import javax.persistence.PersistenceContext;
|
import javax.persistence.PersistenceContext;
|
||||||
|
@ -13,7 +11,6 @@ import java.util.stream.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||||
|
|
||||||
@PersistenceContext
|
@PersistenceContext
|
||||||
private EntityManager entityManager;
|
private EntityManager entityManager;
|
||||||
|
|
||||||
|
@ -48,5 +45,4 @@ public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||||
|
|
||||||
return allUsersStream.collect(Collectors.toList());
|
return allUsersStream.collect(Collectors.toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,12 +1,13 @@
|
||||||
package com.baeldung.spring.transactional;
|
package com.baeldung.spring.data.jpa.query.datetime;
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
class TransactionalCompareApplication {
|
public class Application {
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(TransactionalCompareApplication.class, args);
|
SpringApplication.run(Application.class, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.boot.domain;
|
package com.baeldung.spring.data.jpa.query.datetime;
|
||||||
|
|
||||||
import javax.persistence.*;
|
import javax.persistence.*;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
|
@ -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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
import com.baeldung.boot.domain.Article;
|
|
||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
|
@ -1,11 +1,4 @@
|
||||||
package com.baeldung.boot.daos;
|
package com.baeldung.spring.data.jpa.query.datetime;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.junit.runner.RunWith;
|
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.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||||
import org.springframework.test.context.junit4.SpringRunner;
|
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)
|
@RunWith(SpringRunner.class)
|
||||||
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
|
@ -3,7 +3,6 @@
|
||||||
This module contains articles about querying data using Spring Data JPA
|
This module contains articles about querying data using Spring Data JPA
|
||||||
|
|
||||||
### Relevant Articles:
|
### 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)
|
- [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)
|
- [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)
|
- [Limiting Query Results with JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results)
|
||||||
|
|
|
@ -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/)
|
|
@ -0,0 +1,47 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
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">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-boot-2</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-2</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>spring-data-jpa-repo-2</artifactId>
|
||||||
|
<name>spring-data-jpa-repo-2</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- Persistence -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>javax.persistence</groupId>
|
||||||
|
<artifactId>javax.persistence-api</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.data</groupId>
|
||||||
|
<artifactId>spring-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Utilities -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.guava</groupId>
|
||||||
|
<artifactId>guava</artifactId>
|
||||||
|
<version>${guava.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<guava.version>29.0-jre</guava.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -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 java.io.Serializable;
|
||||||
|
|
||||||
import javax.persistence.Column;
|
|
||||||
import javax.persistence.Entity;
|
|
||||||
import javax.persistence.GeneratedValue;
|
|
||||||
import javax.persistence.GenerationType;
|
|
||||||
import javax.persistence.Id;
|
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
public class Foo implements Serializable {
|
public class Foo implements Serializable {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
@GeneratedValue(strategy = GenerationType.AUTO)
|
||||||
private long id;
|
private long id;
|
||||||
|
@ -28,8 +22,6 @@ public class Foo implements Serializable {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// API
|
|
||||||
|
|
||||||
public long getId() {
|
public long getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
@ -46,8 +38,6 @@ public class Foo implements Serializable {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
//
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int hashCode() {
|
public int hashCode() {
|
||||||
final int prime = 31;
|
final int prime = 31;
|
||||||
|
@ -79,5 +69,4 @@ public class Foo implements Serializable {
|
||||||
builder.append("Foo [name=").append(name).append("]");
|
builder.append("Foo [name=").append(name).append("]");
|
||||||
return builder.toString();
|
return builder.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,13 +1,13 @@
|
||||||
package com.baeldung.spring.data.persistence.repository;
|
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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
|
|
||||||
public interface IFooDao extends JpaRepository<Foo, Long> {
|
public interface IFooDAO extends JpaRepository<Foo, Long> {
|
||||||
|
|
||||||
|
Foo findByName(String name);
|
||||||
|
|
||||||
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
|
||||||
Foo retrieveByName(@Param("name") String name);
|
Foo retrieveByName(@Param("name") String name);
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1,5 @@
|
||||||
|
package com.baeldung.spring.data.persistence.repository;
|
||||||
|
|
||||||
|
public interface IFooService {
|
||||||
|
Foo create(Foo foo);
|
||||||
|
}
|
|
@ -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 com.google.common.base.Preconditions;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
@ -20,11 +20,11 @@ import javax.sql.DataSource;
|
||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
|
@PropertySource("classpath:persistence.properties")
|
||||||
|
@ComponentScan("com.baeldung.spring.data.persistence.repository")
|
||||||
|
//@ImportResource("classpath*:*springDataConfig.xml")
|
||||||
@EnableTransactionManagement
|
@EnableTransactionManagement
|
||||||
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
|
@EnableJpaRepositories(basePackages = "com.baeldung.spring.data.persistence.repository")
|
||||||
@ComponentScan({ "com.baeldung.spring.data.persistence" })
|
|
||||||
//@ImportResource("classpath*:*springDataJpaRepositoriesConfig.xml")
|
|
||||||
@EnableJpaRepositories("com.baeldung.spring.data.persistence.repository")
|
|
||||||
public class PersistenceConfig {
|
public class PersistenceConfig {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
|
@ -38,7 +38,7 @@ public class PersistenceConfig {
|
||||||
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
|
||||||
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
|
||||||
em.setDataSource(dataSource());
|
em.setDataSource(dataSource());
|
||||||
em.setPackagesToScan("com.baeldung.spring.data.persistence.model");
|
em.setPackagesToScan("com.baeldung.spring.data.persistence.repository");
|
||||||
|
|
||||||
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
|
||||||
em.setJpaVendorAdapter(vendorAdapter);
|
em.setJpaVendorAdapter(vendorAdapter);
|
||||||
|
@ -78,5 +78,4 @@ public class PersistenceConfig {
|
||||||
|
|
||||||
return hibernateProperties;
|
return hibernateProperties;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
|
@ -0,0 +1,3 @@
|
||||||
|
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
|
||||||
|
spring.datasource.username=sa
|
||||||
|
spring.datasource.password=sa
|
|
@ -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
|
|
@ -7,7 +7,5 @@
|
||||||
http://www.springframework.org/schema/data/jpa
|
http://www.springframework.org/schema/data/jpa
|
||||||
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
|
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
|
||||||
>
|
>
|
||||||
|
|
||||||
<jpa:repositories base-package="com.baeldung.spring.data.persistence.repository"/>
|
<jpa:repositories base-package="com.baeldung.spring.data.persistence.repository"/>
|
||||||
|
|
||||||
</beans>
|
</beans>
|
|
@ -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());
|
||||||
|
}
|
||||||
|
}
|
|
@ -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 Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories)
|
||||||
- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators)
|
- [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)
|
- [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
|
### Eclipse Config
|
||||||
After importing the project into Eclipse, you may see the following error:
|
After importing the project into Eclipse, you may see the following error:
|
||||||
|
|
|
@ -20,10 +20,9 @@
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.springframework.data</groupId>
|
<groupId>org.mongodb</groupId>
|
||||||
<artifactId>spring-data-releasetrain</artifactId>
|
<artifactId>mongodb-driver-sync</artifactId>
|
||||||
<version>${spring-releasetrain}</version>
|
<version>${mongodb-driver.version}</version>
|
||||||
<type>pom</type>
|
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<dependency>
|
<dependency>
|
||||||
|
@ -66,6 +65,12 @@
|
||||||
<groupId>com.querydsl</groupId>
|
<groupId>com.querydsl</groupId>
|
||||||
<artifactId>querydsl-mongodb</artifactId>
|
<artifactId>querydsl-mongodb</artifactId>
|
||||||
<version>${querydsl.version}</version>
|
<version>${querydsl.version}</version>
|
||||||
|
<exclusions>
|
||||||
|
<exclusion>
|
||||||
|
<groupId>org.mongodb</groupId>
|
||||||
|
<artifactId>mongo-java-driver</artifactId>
|
||||||
|
</exclusion>
|
||||||
|
</exclusions>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.querydsl</groupId>
|
<groupId>com.querydsl</groupId>
|
||||||
|
@ -96,12 +101,12 @@
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<org.springframework.data.version>2.1.9.RELEASE</org.springframework.data.version>
|
<org.springframework.data.version>3.0.3.RELEASE</org.springframework.data.version>
|
||||||
<querydsl.version>4.1.4</querydsl.version>
|
<querydsl.version>4.3.1</querydsl.version>
|
||||||
<mysema.maven.version>1.1.3</mysema.maven.version>
|
<mysema.maven.version>1.1.3</mysema.maven.version>
|
||||||
<mongodb-reactivestreams.version>1.9.2</mongodb-reactivestreams.version>
|
<mongodb-reactivestreams.version>4.1.0</mongodb-reactivestreams.version>
|
||||||
<projectreactor.version>3.2.0.RELEASE</projectreactor.version>
|
<projectreactor.version>3.2.0.RELEASE</projectreactor.version>
|
||||||
<spring-releasetrain>Lovelace-SR9</spring-releasetrain>
|
<mongodb-driver.version>4.0.5</mongodb-driver.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -1,16 +1,18 @@
|
||||||
package com.baeldung.config;
|
package com.baeldung.config;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.Collections;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import converter.ZonedDateTimeReadConverter;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import converter.ZonedDateTimeWriteConverter;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.core.convert.converter.Converter;
|
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.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.core.convert.MongoCustomConversions;
|
||||||
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
|
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
|
||||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
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.converter.UserWriterConverter;
|
||||||
import com.baeldung.event.CascadeSaveMongoEventListener;
|
import com.baeldung.event.CascadeSaveMongoEventListener;
|
||||||
import com.baeldung.event.UserCascadeSaveMongoEventListener;
|
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
|
@Configuration
|
||||||
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
|
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
|
||||||
public class MongoConfig extends AbstractMongoConfiguration {
|
public class MongoConfig extends AbstractMongoClientConfiguration {
|
||||||
|
|
||||||
private final List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
|
private final List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MappingMongoConverter mongoConverter;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected String getDatabaseName() {
|
protected String getDatabaseName() {
|
||||||
return "test";
|
return "test";
|
||||||
|
@ -33,12 +44,16 @@ public class MongoConfig extends AbstractMongoConfiguration {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public MongoClient mongoClient() {
|
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
|
@Override
|
||||||
public String getMappingBasePackage() {
|
public Collection<String> getMappingBasePackages() {
|
||||||
return "com.baeldung";
|
return Collections.singleton("com.baeldung");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
|
@ -61,12 +76,12 @@ public class MongoConfig extends AbstractMongoConfiguration {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public GridFsTemplate gridFsTemplate() throws Exception {
|
public GridFsTemplate gridFsTemplate() throws Exception {
|
||||||
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
|
return new GridFsTemplate(mongoDbFactory(), mongoConverter);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
|
MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
|
||||||
return new MongoTransactionManager(dbFactory);
|
return new MongoTransactionManager(dbFactory);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,7 +5,10 @@ import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
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
|
@Configuration
|
||||||
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
|
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
|
||||||
|
@ -13,7 +16,9 @@ public class SimpleMongoConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public MongoClient mongo() throws Exception {
|
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
|
@Bean
|
||||||
|
|
|
@ -12,7 +12,7 @@
|
||||||
|
|
||||||
<mongo:mongo-client id="mongoClient" host="localhost" />
|
<mongo:mongo-client id="mongoClient" host="localhost" />
|
||||||
|
|
||||||
<mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongoClient" />
|
<mongo:db-factory id="mongoDbFactory" dbname="test" mongo-client-ref="mongoClient" />
|
||||||
|
|
||||||
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
|
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
|
||||||
<constructor-arg ref="mongoDbFactory" />
|
<constructor-arg ref="mongoDbFactory" />
|
||||||
|
|
|
@ -40,7 +40,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||||
|
|
||||||
import com.baeldung.aggregation.model.StatePopulation;
|
import com.baeldung.aggregation.model.StatePopulation;
|
||||||
import com.baeldung.config.MongoConfig;
|
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.MongoCollection;
|
||||||
import com.mongodb.client.MongoDatabase;
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
|
||||||
|
@ -61,7 +64,7 @@ public class ZipsAggregationLiveTest {
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
public static void setupTests() throws Exception {
|
public static void setupTests() throws Exception {
|
||||||
client = new MongoClient();
|
client = mongoClient();
|
||||||
MongoDatabase testDB = client.getDatabase("test");
|
MongoDatabase testDB = client.getDatabase("test");
|
||||||
MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
|
MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
|
||||||
zipsCollection.drop();
|
zipsCollection.drop();
|
||||||
|
@ -75,19 +78,25 @@ public class ZipsAggregationLiveTest {
|
||||||
|
|
||||||
@AfterClass
|
@AfterClass
|
||||||
public static void tearDown() throws Exception {
|
public static void tearDown() throws Exception {
|
||||||
client = new MongoClient();
|
client = mongoClient();
|
||||||
MongoDatabase testDB = client.getDatabase("test");
|
MongoDatabase testDB = client.getDatabase("test");
|
||||||
MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
|
MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
|
||||||
zipsCollection.drop();
|
zipsCollection.drop();
|
||||||
client.close();
|
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
|
@Test
|
||||||
public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() {
|
public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() {
|
||||||
|
|
||||||
GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop");
|
GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop");
|
||||||
MatchOperation filterStates = match(new Criteria("statePop").gt(10000000));
|
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);
|
Aggregation aggregation = newAggregation(groupByStateAndSumPop, filterStates, sortByPopDesc);
|
||||||
AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
|
AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
|
||||||
|
@ -119,7 +128,7 @@ public class ZipsAggregationLiveTest {
|
||||||
|
|
||||||
GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop");
|
GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop");
|
||||||
GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop");
|
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")
|
ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state")
|
||||||
.andExpression("avgCityPop").as("statePop");
|
.andExpression("avgCityPop").as("statePop");
|
||||||
LimitOperation limitToOnlyFirstDoc = limit(1);
|
LimitOperation limitToOnlyFirstDoc = limit(1);
|
||||||
|
|
|
@ -113,7 +113,7 @@ public class GridFSLiveTest {
|
||||||
assertNotNull(gridFSFile.getUploadDate());
|
assertNotNull(gridFSFile.getUploadDate());
|
||||||
// assertNull(gridFSFile.getAliases());
|
// assertNull(gridFSFile.getAliases());
|
||||||
assertNotNull(gridFSFile.getChunkSize());
|
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.getFilename(), is("test.png"));
|
||||||
assertThat(gridFSFile.getMetadata().get("user"), is("alex"));
|
assertThat(gridFSFile.getMetadata().get("user"), is("alex"));
|
||||||
}
|
}
|
||||||
|
|
|
@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.domain.Sort;
|
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.MongoTemplate;
|
||||||
import org.springframework.data.mongodb.core.query.Criteria;
|
import org.springframework.data.mongodb.core.query.Criteria;
|
||||||
import org.springframework.data.mongodb.core.query.Query;
|
import org.springframework.data.mongodb.core.query.Query;
|
||||||
|
@ -186,7 +187,7 @@ public class DocumentQueryLiveTest {
|
||||||
mongoTemplate.insert(user);
|
mongoTemplate.insert(user);
|
||||||
|
|
||||||
Query query = new Query();
|
Query query = new Query();
|
||||||
query.with(new Sort(Sort.Direction.ASC, "age"));
|
query.with(Sort.by(Direction.ASC, "age"));
|
||||||
|
|
||||||
List<User> users = mongoTemplate.find(query, User.class);
|
List<User> users = mongoTemplate.find(query, User.class);
|
||||||
|
|
||||||
|
|
|
@ -137,7 +137,7 @@ public class MongoTemplateQueryLiveTest {
|
||||||
mongoTemplate.insert(user);
|
mongoTemplate.insert(user);
|
||||||
|
|
||||||
Query query = new Query();
|
Query query = new Query();
|
||||||
query.with(new Sort(Sort.Direction.ASC, "age"));
|
query.with(Sort.by(Direction.ASC, "age"));
|
||||||
|
|
||||||
List<User> users = mongoTemplate.find(query, User.class);
|
List<User> users = mongoTemplate.find(query, User.class);
|
||||||
assertThat(users.size(), is(3));
|
assertThat(users.size(), is(3));
|
||||||
|
|
|
@ -14,6 +14,7 @@ import org.springframework.data.domain.Page;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.data.domain.Sort;
|
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.MongoOperations;
|
||||||
import org.springframework.data.mongodb.core.query.Criteria;
|
import org.springframework.data.mongodb.core.query.Criteria;
|
||||||
import org.springframework.data.mongodb.core.query.Query;
|
import org.springframework.data.mongodb.core.query.Query;
|
||||||
|
@ -127,7 +128,7 @@ public class UserRepositoryLiveTest {
|
||||||
user.setName("Adam");
|
user.setName("Adam");
|
||||||
mongoOps.insert(user);
|
mongoOps.insert(user);
|
||||||
|
|
||||||
final List<User> users = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
final List<User> users = userRepository.findAll(Sort.by(Direction.ASC, "name"));
|
||||||
|
|
||||||
assertThat(users.size(), is(2));
|
assertThat(users.size(), is(2));
|
||||||
assertThat(users.get(0).getName(), is("Adam"));
|
assertThat(users.get(0).getName(), is("Adam"));
|
||||||
|
|
|
@ -2,7 +2,6 @@ package com.baeldung.transaction;
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.is;
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
import static org.junit.Assert.assertThat;
|
import static org.junit.Assert.assertThat;
|
||||||
import static org.junit.Assert.assertTrue;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
@ -22,7 +21,6 @@ import org.springframework.transaction.annotation.Transactional;
|
||||||
import com.baeldung.config.MongoConfig;
|
import com.baeldung.config.MongoConfig;
|
||||||
import com.baeldung.model.User;
|
import com.baeldung.model.User;
|
||||||
import com.baeldung.repository.UserRepository;
|
import com.baeldung.repository.UserRepository;
|
||||||
import com.mongodb.MongoCommandException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
|
|
|
@ -8,9 +8,9 @@
|
||||||
|
|
||||||
<parent>
|
<parent>
|
||||||
<groupId>com.baeldung</groupId>
|
<groupId>com.baeldung</groupId>
|
||||||
<artifactId>parent-spring-4</artifactId>
|
<artifactId>parent-spring-5</artifactId>
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
<relativePath>../../parent-spring-4</relativePath>
|
<relativePath>../../parent-spring-5</relativePath>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
|
|
@ -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)
|
|
@ -0,0 +1,41 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
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">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>com.baeldung</groupId>
|
||||||
|
<artifactId>parent-boot-2</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
<relativePath>../../parent-boot-2</relativePath>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>spring-jdbc</artifactId>
|
||||||
|
<name>spring-jdbc</name>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.data</groupId>
|
||||||
|
<artifactId>spring-data-jdbc</artifactId>
|
||||||
|
<version>${spring-data-jdbc.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-java</artifactId>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<spring-data-jdbc.version>2.0.3.RELEASE</spring-data-jdbc.version>
|
||||||
|
</properties>
|
||||||
|
</project>
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.autogenkey.config;
|
package com.baeldung.spring.jdbc.autogenkey.config;
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
@ -16,7 +16,7 @@ public class PersistenceConfig {
|
||||||
public DataSource dataSource(Environment env) {
|
public DataSource dataSource(Environment env) {
|
||||||
return new EmbeddedDatabaseBuilder()
|
return new EmbeddedDatabaseBuilder()
|
||||||
.setType(EmbeddedDatabaseType.H2)
|
.setType(EmbeddedDatabaseType.H2)
|
||||||
.addScript("autogenkey-schema.sql")
|
.addScript("com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql")
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.autogenkey.repository;
|
package com.baeldung.spring.jdbc.autogenkey.repository;
|
||||||
|
|
||||||
import java.sql.PreparedStatement;
|
import java.sql.PreparedStatement;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.autogenkey.repository;
|
package com.baeldung.spring.jdbc.autogenkey.repository;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc.template.guide;
|
||||||
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc.template.guide;
|
||||||
|
|
||||||
public class Employee {
|
public class Employee {
|
||||||
private int id;
|
private int id;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc.template.guide;
|
||||||
|
|
||||||
import java.sql.PreparedStatement;
|
import java.sql.PreparedStatement;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc;
|
package com.baeldung.spring.jdbc.template.guide;
|
||||||
|
|
||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
|
@ -1,4 +1,4 @@
|
||||||
package com.baeldung.jdbc.config;
|
package com.baeldung.spring.jdbc.template.guide.config;
|
||||||
|
|
||||||
import javax.sql.DataSource;
|
import javax.sql.DataSource;
|
||||||
|
|
||||||
|
@ -10,12 +10,16 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@ComponentScan("com.baeldung.jdbc")
|
@ComponentScan("com.baeldung.spring.jdbc")
|
||||||
public class SpringJdbcConfig {
|
public class SpringJdbcConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public DataSource dataSource() {
|
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
|
// @Bean
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue