Merge pull request #4 from eugenp/master

merge
This commit is contained in:
marcodenisi 2020-09-03 16:46:59 +02:00 committed by GitHub
commit 2133920f2a
318 changed files with 3266 additions and 3206 deletions

3
.gitignore vendored
View File

@ -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

View File

@ -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>

View File

@ -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;
}
}

View File

@ -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
}
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}

View File

@ -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>

View File

@ -0,0 +1,7 @@
## Core Kotlin Collections
This module contains articles about core Kotlin collections.
### Relevant articles:

View File

@ -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>

View File

@ -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
}
}

View File

@ -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())
}
}

View File

@ -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>

View File

@ -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)

View File

@ -1,3 +1,4 @@
rootProject.name='gradle-5-articles' rootProject.name='gradle-5-articles'
include 'java-exec' include 'java-exec'
include 'unused-dependencies' include 'unused-dependencies'
include 'source-sets'

1
gradle-5/source-sets/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/build/

View File

@ -0,0 +1,67 @@
apply plugin: "eclipse"
apply plugin: "java"
description = "Source Sets example"
task printSourceSetInformation(){
description = "Print source set information"
doLast{
sourceSets.each { srcSet ->
println "["+srcSet.name+"]"
print "-->Source directories: "+srcSet.allJava.srcDirs+"\n"
print "-->Output directories: "+srcSet.output.classesDirs.files+"\n"
print "-->Compile classpath:\n"
srcSet.compileClasspath.files.each {
print " "+it.path+"\n"
}
println ""
}
}
}
sourceSets{
itest {
compileClasspath += sourceSets.main.output
runtimeClasspath += sourceSets.main.output
java {
}
}
}
test {
testLogging {
events "passed","skipped", "failed"
}
}
dependencies {
implementation('org.apache.httpcomponents:httpclient:4.5.12')
testImplementation('junit:junit:4.12')
itestImplementation('com.google.guava:guava:29.0-jre')
}
task itest(type: Test) {
description = "Run integration tests"
group = "verification"
testClassesDirs = sourceSets.itest.output.classesDirs
classpath = sourceSets.itest.runtimeClasspath
}
itest {
testLogging {
events "passed","skipped", "failed"
}
}
configurations {
itestImplementation.extendsFrom(testImplementation)
itestRuntimeOnly.extendsFrom(testRuntimeOnly)
}
eclipse {
classpath {
plusConfigurations+=[configurations.itestCompileClasspath]
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.itest;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
import com.baeldung.main.SourceSetsObject;
import com.google.common.collect.ImmutableList;
public class SourceSetsItest {
@Test
public void givenImmutableList_whenRun_ThenSuccess() {
SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum");
List<String> someStrings = ImmutableList.of("Baeldung", "is", "cool");
assertThat(underTest.getUser(), is("lorem"));
assertThat(underTest.getPassword(), is("ipsum"));
assertThat(someStrings.size(), is(3));
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.main;
public class SourceSetsMain {
public static void main(String[] args) {
System.out.println("Hell..oh...world!");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.main;
public class SourceSetsObject {
private final String user;
private final String password;
public SourceSetsObject(String user, String password) {
this.user = user;
this.password = password;
}
public String getPassword() {
return password;
}
public String getUser() {
return user;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import com.baeldung.main.SourceSetsObject;
public class SourceSetsTest {
@Test
public void whenRun_ThenSuccess() {
SourceSetsObject underTest = new SourceSetsObject("lorem", "ipsum");
assertThat(underTest.getUser(), is("lorem"));
assertThat(underTest.getPassword(), is("ipsum"));
}
}

View File

@ -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>

View File

@ -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>

View File

@ -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>

View File

@ -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(5L, 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();
}
}
}

View File

@ -0,0 +1,52 @@
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;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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

View File

@ -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;

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc;
import java.util.Objects; import java.util.Objects;

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbc.joins; package com.baeldung.spring.jdbc.joins;
class ArticleWithAuthor { class ArticleWithAuthor {

View File

@ -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;

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc;
import static org.junit.Assert.*; import static org.junit.Assert.*;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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>

View File

@ -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

View File

@ -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>

View File

@ -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>

View File

@ -4,6 +4,7 @@ This module contains articles about querying data using Spring Data JPA
### Relevant Articles: ### Relevant Articles:
- [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

View File

@ -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>

View File

@ -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;
}
} }

View File

@ -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();
} }

View File

@ -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;

View File

@ -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)

View File

@ -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/)

View File

@ -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>

View File

@ -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();
} }
} }

View File

@ -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);
}
}

View File

@ -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);
} }

View File

@ -0,0 +1,5 @@
package com.baeldung.spring.data.persistence.repository;
public interface IFooService {
Foo create(Foo foo);
}

View File

@ -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;
} }
} }

View File

@ -0,0 +1,3 @@
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

View File

@ -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

View File

@ -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>

View File

@ -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());
}
}

View File

@ -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:

View File

@ -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)

View File

@ -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>

View File

@ -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();
} }

View File

@ -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;

View File

@ -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;

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc.template.guide;
import java.sql.SQLException; import java.sql.SQLException;

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -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

View File

@ -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;
}
}

View File

@ -1,10 +1,4 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc.template.inclause;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
@ -12,6 +6,11 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Repository @Repository
public class EmployeeDAO { public class EmployeeDAO {
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@ -22,10 +21,6 @@ public class EmployeeDAO {
namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
} }
public int getCountOfEmployees() {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class);
}
public List<Employee> getEmployeesFromIdListNamed(List<Integer> ids) { public List<Employee> getEmployeesFromIdListNamed(List<Integer> ids) {
SqlParameterSource parameters = new MapSqlParameterSource("ids", ids); SqlParameterSource parameters = new MapSqlParameterSource("ids", ids);
List<Employee> employees = namedJdbcTemplate.query( List<Employee> employees = namedJdbcTemplate.query(
@ -63,5 +58,4 @@ public class EmployeeDAO {
return employees; return employees;
} }
} }

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc.template.testing;
public class Employee { public class Employee {
private int id; private int id;

View File

@ -0,0 +1,19 @@
package com.baeldung.spring.jdbc.template.testing;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
@Repository
public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public int getCountOfEmployees() {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class);
}
}

View File

@ -0,0 +1,3 @@
spring.datasource.url=jdbc:mysql://localhost:3306/springjdbc
spring.datasource.username=guest_user
spring.datasource.password=guest_password

View File

@ -0,0 +1,7 @@
CREATE TABLE EMPLOYEE
(
ID int NOT NULL PRIMARY KEY,
FIRST_NAME varchar(255),
LAST_NAME varchar(255),
ADDRESS varchar(255)
);

View File

@ -0,0 +1,7 @@
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');

View File

@ -0,0 +1,7 @@
CREATE TABLE EMPLOYEE
(
ID int NOT NULL PRIMARY KEY,
FIRST_NAME varchar(255),
LAST_NAME varchar(255),
ADDRESS varchar(255)
);

View File

@ -0,0 +1,7 @@
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');

View File

@ -1,4 +1,4 @@
package com.baeldung.jdbc.autogenkey; package com.baeldung.spring.jdbc.autogenkey;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -7,16 +7,17 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate;
import com.baeldung.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert; import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositorySimpleJDBCInsert;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
public class GetAutoGenKeyByJDBC { public class GetAutoGenKeyByJDBC {
@Configuration @Configuration
@ComponentScan(basePackages = { "com.baeldung.jdbc.autogenkey" }) @ComponentScan(basePackages = {"com.baeldung.spring.jdbc.autogenkey"})
public static class SpringConfig { public static class SpringConfig {
} }
@ -35,7 +36,6 @@ public class GetAutoGenKeyByJDBC {
String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key); String loadedMessage = messageRepositoryJDBCTemplate.getMessageById(key);
assertEquals(MESSAGE_CONTENT, loadedMessage); assertEquals(MESSAGE_CONTENT, loadedMessage);
} }
@Test @Test

View File

@ -1,9 +1,11 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc.template.guide;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.baeldung.jdbc.config.SpringJdbcConfig; import com.baeldung.spring.jdbc.template.guide.Employee;
import com.baeldung.spring.jdbc.template.guide.EmployeeDAO;
import com.baeldung.spring.jdbc.template.guide.config.SpringJdbcConfig;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;

View File

@ -1,22 +1,19 @@
package com.baeldung.jdbc; package com.baeldung.spring.jdbc.template.inclause;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.util.ReflectionTestUtils;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
@ -30,33 +27,9 @@ public class EmployeeDAOUnitTest {
public void setup() { public void setup() {
dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.generateUniqueName(true) .generateUniqueName(true)
.addScript("classpath:jdbc/schema.sql") .addScript("classpath:com/baeldung/spring/jdbc/template/inclause/schema.sql")
.addScript("classpath:jdbc/test-data.sql") .addScript("classpath:com/baeldung/spring/jdbc/template/inclause/test-data.sql")
.build(); .build();
}
@Test
public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() {
EmployeeDAO employeeDAO = new EmployeeDAO();
ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate);
Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class))
.thenReturn(4);
assertEquals(4, employeeDAO.getCountOfEmployees());
Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class)))
.thenReturn(3);
assertEquals(3, employeeDAO.getCountOfEmployees());
}
@Test
public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() {
EmployeeDAO employeeDAO = new EmployeeDAO();
employeeDAO.setDataSource(dataSource);
assertEquals(4, employeeDAO.getCountOfEmployees());
} }
@Test @Test

View File

@ -0,0 +1,56 @@
package com.baeldung.spring.jdbc.template.testing;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.test.util.ReflectionTestUtils;
import javax.sql.DataSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class EmployeeDAOUnitTest {
@Mock
JdbcTemplate jdbcTemplate;
DataSource dataSource;
@Before
public void setup() {
dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.generateUniqueName(true)
.addScript("classpath:com/baeldung/spring/jdbc/template/testing/schema.sql")
.addScript("classpath:com/baeldung/spring/jdbc/template/testing/test-data.sql")
.build();
}
@Test
public void whenMockJdbcTemplate_thenReturnCorrectEmployeeCount() {
EmployeeDAO employeeDAO = new EmployeeDAO();
ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate);
Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class))
.thenReturn(4);
assertEquals(4, employeeDAO.getCountOfEmployees());
Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class)))
.thenReturn(3);
assertEquals(3, employeeDAO.getCountOfEmployees());
}
@Test
public void whenInjectInMemoryDataSource_thenReturnCorrectEmployeeCount() {
EmployeeDAO employeeDAO = new EmployeeDAO();
employeeDAO.setDataSource(dataSource);
assertEquals(4, employeeDAO.getCountOfEmployees());
}
}

View File

@ -2,4 +2,9 @@
### Relevant Articles: ### Relevant Articles:
- [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many) - [Many-To-Many Relationship in JPA](https://www.baeldung.com/jpa-many-to-many)
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Bootstrapping Hibernate 5 with Spring](https://www.baeldung.com/hibernate-5-spring)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
- More articles: [[<-- prev]](/spring-jpa) - More articles: [[<-- prev]](/spring-jpa)

View File

@ -15,6 +15,17 @@
<dependencies> <dependencies>
<!-- Spring --> <!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId> <artifactId>spring-orm</artifactId>
@ -43,8 +54,25 @@
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
<version>${h2.version}</version> <version>${h2.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<!-- utilities -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped --> <!-- test scoped -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId> <artifactId>spring-test</artifactId>
@ -57,6 +85,13 @@
<properties> <properties>
<!-- Spring --> <!-- Spring -->
<org.springframework.version>5.1.5.RELEASE</org.springframework.version> <org.springframework.version>5.1.5.RELEASE</org.springframework.version>
<!-- persistence -->
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<!-- utilities -->
<guava.version>21.0</guava.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
</properties> </properties>
</project> </project>

View File

@ -51,7 +51,7 @@ public class HibernateConf {
return transactionManager; return transactionManager;
} }
private final Properties hibernateProperties() { private Properties hibernateProperties() {
final Properties hibernateProperties = new Properties(); final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));

View File

@ -1,52 +1,49 @@
package com.baeldung.persistence.dao.common; package com.baeldung.spring.dao.generics;
import java.io.Serializable;
import java.util.List;
import com.google.common.base.Preconditions;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import com.google.common.base.Preconditions; import java.io.Serializable;
import java.util.List;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public abstract class AbstractHibernateDao<T extends Serializable> extends AbstractDao<T> implements IOperations<T> { public abstract class AbstractHibernateDao<T extends Serializable> {
private Class<T> clazz;
@Autowired @Autowired
protected SessionFactory sessionFactory; protected SessionFactory sessionFactory;
// API public void setClazz(final Class<T> clazzToSet) {
clazz = Preconditions.checkNotNull(clazzToSet);
}
@Override // API
public T findOne(final long id) { public T findOne(final long id) {
return (T) getCurrentSession().get(clazz, id); return (T) getCurrentSession().get(clazz, id);
} }
@Override
public List<T> findAll() { public List<T> findAll() {
return getCurrentSession().createQuery("from " + clazz.getName()).list(); return getCurrentSession().createQuery("from " + clazz.getName()).list();
} }
@Override
public T create(final T entity) { public T create(final T entity) {
Preconditions.checkNotNull(entity); Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity); getCurrentSession().saveOrUpdate(entity);
return entity; return entity;
} }
@Override
public T update(final T entity) { public T update(final T entity) {
Preconditions.checkNotNull(entity); Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity); return (T) getCurrentSession().merge(entity);
} }
@Override
public void delete(final T entity) { public void delete(final T entity) {
Preconditions.checkNotNull(entity); Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity); getCurrentSession().delete(entity);
} }
@Override
public void deleteById(final long entityId) { public void deleteById(final long entityId) {
final T entity = findOne(entityId); final T entity = findOne(entityId);
Preconditions.checkState(entity != null); Preconditions.checkState(entity != null);
@ -56,5 +53,4 @@ public abstract class AbstractHibernateDao<T extends Serializable> extends Abstr
protected Session getCurrentSession() { protected Session getCurrentSession() {
return sessionFactory.getCurrentSession(); return sessionFactory.getCurrentSession();
} }
} }

View File

@ -1,4 +1,4 @@
package com.baeldung.jpa.dao; package com.baeldung.spring.dao.generics;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
@ -6,7 +6,6 @@ import java.io.Serializable;
import java.util.List; import java.util.List;
public abstract class AbstractJpaDAO<T extends Serializable> { public abstract class AbstractJpaDAO<T extends Serializable> {
private Class<T> clazz; private Class<T> clazz;
@PersistenceContext(unitName = "entityManagerFactory") @PersistenceContext(unitName = "entityManagerFactory")
@ -42,5 +41,4 @@ public abstract class AbstractJpaDAO<T extends Serializable> {
final T entity = findOne(entityId); final T entity = findOne(entityId);
delete(entity); delete(entity);
} }
} }

View File

@ -1,21 +1,10 @@
package com.baeldung.persistence.model; package com.baeldung.spring.dao.generics;
import java.io.Serializable;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
@Entity @Entity
@Cacheable @Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@ -41,18 +30,6 @@ public class Foo implements Serializable {
@Column(name = "NAME") @Column(name = "NAME")
private String name; private String name;
@ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
@JoinColumn(name = "BAR_ID")
private Bar bar;
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public Long getId() { public Long getId() {
return id; return id;
} }
@ -100,5 +77,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();
} }
} }

View File

@ -0,0 +1,21 @@
package com.baeldung.spring.dao.generics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class FooService implements IFooService {
IGenericDao<Foo> dao;
@Autowired
public void setDao(IGenericDao<Foo> daoToSet) {
dao = daoToSet;
dao.setClazz(Foo.class);
}
@Override
public Foo retrieveByName(String name) {
return null;
}
}

View File

@ -1,11 +1,11 @@
package com.baeldung.persistence.dao.common; package com.baeldung.spring.dao.generics;
import java.io.Serializable;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.io.Serializable;
@Repository @Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> { public class GenericHibernateDao<T extends Serializable> extends AbstractHibernateDao<T> implements IGenericDao<T> {

Some files were not shown because too many files have changed in this diff Show More