Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
43c6152b83
11
README.md
11
README.md
|
@ -20,17 +20,22 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
|
|||
|
||||
Building the project
|
||||
====================
|
||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||
To do the full build, do: `mvn clean install`
|
||||
|
||||
|
||||
Building a single module
|
||||
====================
|
||||
To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
|
||||
To build a specific module run the command: `mvn clean install` in the module directory
|
||||
|
||||
|
||||
Running a Spring Boot module
|
||||
====================
|
||||
To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory
|
||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||
|
||||
#Running Tests
|
||||
|
||||
The command `mvn clean install` will run the unit tests in a module.
|
||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -21,7 +21,7 @@ import java.util.stream.Stream;
|
|||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class GeodeSamplesIntegrationTest {
|
||||
public class GeodeSamplesLiveTest {
|
||||
|
||||
ClientCache cache = null;
|
||||
Region<String, String> region = null;
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [OData Protocol Guide](https://www.baeldung.com/odata)
|
|
@ -28,6 +28,6 @@
|
|||
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
|
||||
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
|
||||
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
|
||||
- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api)
|
||||
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
|
||||
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
|
||||
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
|
|
@ -1 +0,0 @@
|
|||
### Relevant Articles:
|
|
@ -19,7 +19,7 @@ public class Graph {
|
|||
|
||||
void removeVertex(String label) {
|
||||
Vertex v = new Vertex(label);
|
||||
adjVertices.values().stream().map(e -> e.remove(v)).collect(Collectors.toList());
|
||||
adjVertices.values().stream().forEach(e -> e.remove(v));
|
||||
adjVertices.remove(new Vertex(label));
|
||||
}
|
||||
|
||||
|
|
|
@ -1,20 +1,31 @@
|
|||
package com.baeldung.graph;
|
||||
|
||||
import org.junit.Assert;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GraphTraversalUnitTest {
|
||||
public class GraphUnitTest {
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]",
|
||||
assertEquals("[Bob, Rob, Maria, Alice, Mark]",
|
||||
GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
|
||||
Graph graph = createGraph();
|
||||
Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAGraph_whenRemoveVertex_thenVertedNotFound() {
|
||||
Graph graph = createGraph();
|
||||
assertEquals("[Bob, Alice, Rob, Mark, Maria]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
|
||||
graph.removeVertex("Maria");
|
||||
assertEquals("[Bob, Alice, Rob, Mark]",
|
||||
GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
|
||||
}
|
||||
|
|
@ -9,19 +9,3 @@ interface Document {
|
|||
|
||||
fun getType() = "document"
|
||||
}
|
||||
|
||||
class TextDocument : Document {
|
||||
override fun getType() = "text"
|
||||
|
||||
fun transformList(list : List<Number>) : List<Number> {
|
||||
return list.filter { n -> n.toInt() > 1 }
|
||||
}
|
||||
|
||||
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
|
||||
return list.filter { n -> n.toInt() > 1 }
|
||||
}
|
||||
|
||||
var list : List<@JvmWildcard Any> = ArrayList()
|
||||
}
|
||||
|
||||
class XmlDocument(d : Document) : Document by d
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package com.baeldung.jvmannotations
|
||||
|
||||
import java.util.*
|
||||
class TextDocument : Document {
|
||||
override fun getType() = "text"
|
||||
|
||||
fun transformList(list : List<Number>) : List<Number> {
|
||||
return list.filter { n -> n.toInt() > 1 }
|
||||
}
|
||||
|
||||
fun transformListInverseWildcards(list : List<@JvmSuppressWildcards Number>) : List<@JvmWildcard Number> {
|
||||
return list.filter { n -> n.toInt() > 1 }
|
||||
}
|
||||
|
||||
var list : List<@JvmWildcard Any> = ArrayList()
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.jvmannotations
|
||||
|
||||
import java.util.*
|
||||
|
||||
class XmlDocument(d : Document) : Document by d
|
|
@ -3,6 +3,8 @@ package com.baeldung.range
|
|||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
import com.baeldung.jvmannotations.*;
|
||||
|
||||
class DocumentTest {
|
||||
|
||||
@Test
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.convertToMap;
|
||||
|
||||
public class Book {
|
||||
private String name;
|
||||
private int releaseYear;
|
||||
private String isbn;
|
||||
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Book{" +
|
||||
"name='" + name + '\'' +
|
||||
", releaseYear=" + releaseYear +
|
||||
", isbn='" + isbn + '\'' +
|
||||
'}';
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getReleaseYear() {
|
||||
return releaseYear;
|
||||
}
|
||||
|
||||
public void setReleaseYear(int releaseYear) {
|
||||
this.releaseYear = releaseYear;
|
||||
}
|
||||
|
||||
public String getIsbn() {
|
||||
return isbn;
|
||||
}
|
||||
|
||||
public void setIsbn(String isbn) {
|
||||
this.isbn = isbn;
|
||||
}
|
||||
|
||||
public Book(String name, int releaseYear, String isbn) {
|
||||
this.name = name;
|
||||
this.releaseYear = releaseYear;
|
||||
this.isbn = isbn;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.convertToMap;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ConvertToMap {
|
||||
public Map<String, String> listToMap(List<Book> books) {
|
||||
return books.stream().collect(Collectors.toMap(Book::getIsbn, Book::getName));
|
||||
}
|
||||
|
||||
public Map<Integer, Book> listToMapWithDupKeyError(List<Book> books) {
|
||||
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity()));
|
||||
}
|
||||
|
||||
public Map<Integer, Book> listToMapWithDupKey(List<Book> books) {
|
||||
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(),
|
||||
(o1, o2) -> o1));
|
||||
}
|
||||
|
||||
public Map<Integer, Book> listToConcurrentMap(List<Book> books) {
|
||||
return books.stream().collect(Collectors.toMap(Book::getReleaseYear, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new));
|
||||
}
|
||||
|
||||
public TreeMap<String, Book> listToSortedMap(List<Book> books) {
|
||||
return books.stream()
|
||||
.sorted(Comparator.comparing(Book::getName))
|
||||
.collect(Collectors.toMap(Book::getName, Function.identity(), (o1, o2) -> o1, TreeMap::new));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package com.baeldung.convertToMap;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
public class ConvertToMapUnitTest {
|
||||
|
||||
private List<Book> bookList;
|
||||
private ConvertToMap convertToMap = new ConvertToMap();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
bookList = new ArrayList<>();
|
||||
bookList.add(new Book("The Fellowship of the Ring", 1954, "0395489318"));
|
||||
bookList.add(new Book("The Two Towers", 1954, "0345339711"));
|
||||
bookList.add(new Book("The Return of the King", 1955, "0618129111"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertFromListToMap() {
|
||||
assertTrue(convertToMap.listToMap(bookList).size() == 3);
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void whenMapHasDuplicateKey_without_merge_function_then_runtime_exception() {
|
||||
convertToMap.listToMapWithDupKeyError(bookList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapHasDuplicateKey_with_merge_function() {
|
||||
assertTrue(convertToMap.listToMapWithDupKey(bookList).size() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateConcurrentHashMap() {
|
||||
assertTrue(convertToMap.listToConcurrentMap(bookList) instanceof ConcurrentHashMap);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMapisSorted() {
|
||||
assertTrue(convertToMap.listToSortedMap(bookList).firstKey().equals("The Fellowship of the Ring"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,120 @@
|
|||
<?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>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>kotlin-quasar</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<name>kotlin-quasar</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-test</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-core</artifactId>
|
||||
<version>${quasar.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-actors</artifactId>
|
||||
<version>${quasar.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-reactive-streams</artifactId>
|
||||
<version>${quasar.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>co.paralleluniverse</groupId>
|
||||
<artifactId>quasar-kotlin</artifactId>
|
||||
<version>${quasar.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.12</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src/main/kotlin</sourceDirectory>
|
||||
<testSourceDirectory>src/test/kotlin</testSourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-maven-plugin</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>compile</id>
|
||||
<phase>compile</phase>
|
||||
<goals>
|
||||
<goal>compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>test-compile</id>
|
||||
<phase>test-compile</phase>
|
||||
<goals>
|
||||
<goal>test-compile</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<jvmTarget>1.8</jvmTarget>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<version>3.1.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>getClasspathFilenames</id>
|
||||
<goals>
|
||||
<goal>properties</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.1</version>
|
||||
<configuration>
|
||||
<argLine>-Dco.paralleluniverse.fibers.verifyInstrumentation=true</argLine>
|
||||
<argLine>-javaagent:${co.paralleluniverse:quasar-core:jar}</argLine>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.3.2</version>
|
||||
<configuration>
|
||||
<workingDirectory>target/classes</workingDirectory>
|
||||
<executable>echo</executable>
|
||||
<arguments>
|
||||
<argument>-javaagent:${co.paralleluniverse:quasar-core:jar}</argument>
|
||||
<argument>-classpath</argument> <classpath/>
|
||||
<argument>com.baeldung.quasar.QuasarHelloWorldKt</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<quasar.version>0.8.0</quasar.version>
|
||||
<kotlin.version>1.3.31</kotlin.version>
|
||||
</properties>
|
||||
</project>
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.quasar
|
||||
|
||||
import co.paralleluniverse.fibers.Fiber
|
||||
import co.paralleluniverse.strands.SuspendableRunnable
|
||||
|
||||
|
||||
/**
|
||||
* Entrypoint into the application
|
||||
*/
|
||||
fun main(args: Array<String>) {
|
||||
class Runnable : SuspendableRunnable {
|
||||
override fun run() {
|
||||
println("Hello")
|
||||
}
|
||||
}
|
||||
val result = Fiber<Void>(Runnable()).start()
|
||||
result.join()
|
||||
println("World")
|
||||
}
|
|
@ -0,0 +1,155 @@
|
|||
package com.baeldung.quasar
|
||||
|
||||
import co.paralleluniverse.fibers.Suspendable
|
||||
import co.paralleluniverse.kotlin.fiber
|
||||
import co.paralleluniverse.strands.channels.Channels
|
||||
import co.paralleluniverse.strands.channels.Selector
|
||||
import com.google.common.base.Function
|
||||
import org.junit.Test
|
||||
|
||||
class ChannelsTest {
|
||||
@Test
|
||||
fun createChannel() {
|
||||
Channels.newChannel<String>(0, // The size of the channel buffer
|
||||
Channels.OverflowPolicy.BLOCK, // The policy for when the buffer is full
|
||||
true, // Whether we should optimize for a single message producer
|
||||
true) // Whether we should optimize for a single message consumer
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blockOnMessage() {
|
||||
val channel = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
|
||||
fiber @Suspendable {
|
||||
while (!channel.isClosed) {
|
||||
val message = channel.receive()
|
||||
println("Received: $message")
|
||||
}
|
||||
println("Stopped receiving messages")
|
||||
}
|
||||
|
||||
channel.send("Hello")
|
||||
channel.send("World")
|
||||
|
||||
channel.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selectReceiveChannels() {
|
||||
val channel1 = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
val channel2 = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
|
||||
fiber @Suspendable {
|
||||
while (!channel1.isClosed && !channel2.isClosed) {
|
||||
val received = Selector.select(Selector.receive(channel1), Selector.receive(channel2))
|
||||
|
||||
println("Received: $received")
|
||||
}
|
||||
}
|
||||
|
||||
fiber @Suspendable {
|
||||
for (i in 0..10) {
|
||||
channel1.send("Channel 1: $i")
|
||||
}
|
||||
}
|
||||
|
||||
fiber @Suspendable {
|
||||
for (i in 0..10) {
|
||||
channel2.send("Channel 2: $i")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun selectSendChannels() {
|
||||
val channel1 = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
val channel2 = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
|
||||
fiber @Suspendable {
|
||||
for (i in 0..10) {
|
||||
Selector.select(
|
||||
Selector.send(channel1, "Channel 1: $i"),
|
||||
Selector.send(channel2, "Channel 2: $i")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fiber @Suspendable {
|
||||
while (!channel1.isClosed) {
|
||||
val msg = channel1.receive()
|
||||
println("Read: $msg")
|
||||
}
|
||||
}
|
||||
|
||||
fiber @Suspendable {
|
||||
while (!channel2.isClosed) {
|
||||
val msg = channel2.receive()
|
||||
println("Read: $msg")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun tickerChannel() {
|
||||
val channel = Channels.newChannel<String>(3, Channels.OverflowPolicy.DISPLACE)
|
||||
|
||||
for (i in 0..10) {
|
||||
val tickerConsumer = Channels.newTickerConsumerFor(channel)
|
||||
fiber @Suspendable {
|
||||
while (!tickerConsumer.isClosed) {
|
||||
val message = tickerConsumer.receive()
|
||||
println("Received on $i: $message")
|
||||
}
|
||||
println("Stopped receiving messages on $i")
|
||||
}
|
||||
}
|
||||
|
||||
for (i in 0..50) {
|
||||
channel.send("Message $i")
|
||||
}
|
||||
|
||||
channel.close()
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
fun transformOnSend() {
|
||||
val channel = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
|
||||
fiber @Suspendable {
|
||||
while (!channel.isClosed) {
|
||||
val message = channel.receive()
|
||||
println("Received: $message")
|
||||
}
|
||||
println("Stopped receiving messages")
|
||||
}
|
||||
|
||||
val transformOnSend = Channels.mapSend(channel, Function<String, String> { msg: String? -> msg?.toUpperCase() })
|
||||
|
||||
transformOnSend.send("Hello")
|
||||
transformOnSend.send("World")
|
||||
|
||||
channel.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun transformOnReceive() {
|
||||
val channel = Channels.newChannel<String>(0, Channels.OverflowPolicy.BLOCK, true, true)
|
||||
|
||||
val transformOnReceive = Channels.map(channel, Function<String, String> { msg: String? -> msg?.reversed() })
|
||||
|
||||
fiber @Suspendable {
|
||||
while (!transformOnReceive.isClosed) {
|
||||
val message = transformOnReceive.receive()
|
||||
println("Received: $message")
|
||||
}
|
||||
println("Stopped receiving messages")
|
||||
}
|
||||
|
||||
|
||||
channel.send("Hello")
|
||||
channel.send("World")
|
||||
|
||||
channel.close()
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.quasar
|
||||
|
||||
import co.paralleluniverse.strands.dataflow.Val
|
||||
import co.paralleluniverse.strands.dataflow.Var
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
class DataflowTest {
|
||||
@Test
|
||||
fun testValVar() {
|
||||
val a = Var<Int>()
|
||||
val b = Val<Int>()
|
||||
|
||||
val c = Var<Int> { a.get() + b.get() }
|
||||
val d = Var<Int> { a.get() * b.get() }
|
||||
|
||||
// (a*b) - (a+b)
|
||||
val initialResult = Val<Int> { d.get() - c.get() }
|
||||
val currentResult = Var<Int> { d.get() - c.get() }
|
||||
|
||||
a.set(2)
|
||||
b.set(4)
|
||||
|
||||
Assert.assertEquals(2, initialResult.get())
|
||||
Assert.assertEquals(2, currentResult.get())
|
||||
|
||||
a.set(3)
|
||||
|
||||
TimeUnit.SECONDS.sleep(1)
|
||||
|
||||
Assert.assertEquals(2, initialResult.get())
|
||||
Assert.assertEquals(5, currentResult.get())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package com.baeldung.quasar
|
||||
|
||||
import co.paralleluniverse.fibers.Fiber
|
||||
import co.paralleluniverse.fibers.FiberAsync
|
||||
import co.paralleluniverse.fibers.Suspendable
|
||||
import co.paralleluniverse.kotlin.fiber
|
||||
import co.paralleluniverse.strands.Strand
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
import java.math.BigDecimal
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
interface PiCallback {
|
||||
fun success(result: BigDecimal)
|
||||
fun failure(error: Exception)
|
||||
}
|
||||
|
||||
fun computePi(callback: PiCallback) {
|
||||
println("Starting calculations")
|
||||
TimeUnit.SECONDS.sleep(2)
|
||||
println("Finished calculations")
|
||||
callback.success(BigDecimal("3.14"))
|
||||
}
|
||||
|
||||
class PiAsync : PiCallback, FiberAsync<BigDecimal, Exception>() {
|
||||
override fun success(result: BigDecimal) {
|
||||
asyncCompleted(result)
|
||||
}
|
||||
|
||||
override fun failure(error: Exception) {
|
||||
asyncFailed(error)
|
||||
}
|
||||
|
||||
override fun requestAsync() {
|
||||
computePi(this)
|
||||
}
|
||||
}
|
||||
|
||||
class PiAsyncTest {
|
||||
@Test
|
||||
fun testPi() {
|
||||
val result = fiber @Suspendable {
|
||||
val pi = PiAsync()
|
||||
println("Waiting to get PI on: " + Fiber.currentFiber().name)
|
||||
val result = pi.run()
|
||||
println("Got PI")
|
||||
|
||||
result
|
||||
}.get()
|
||||
|
||||
Assert.assertEquals(BigDecimal("3.14"), result)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.quasar
|
||||
|
||||
import co.paralleluniverse.fibers.Fiber
|
||||
import co.paralleluniverse.fibers.Suspendable
|
||||
import co.paralleluniverse.kotlin.fiber
|
||||
import co.paralleluniverse.strands.SuspendableCallable
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
|
||||
class SuspendableCallableTest {
|
||||
@Test
|
||||
fun createFiber() {
|
||||
class Callable : SuspendableCallable<String> {
|
||||
override fun run(): String {
|
||||
println("Inside Fiber")
|
||||
return "Hello"
|
||||
}
|
||||
}
|
||||
val result = Fiber<String>(Callable()).start()
|
||||
|
||||
Assert.assertEquals("Hello", result.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createFiberLambda() {
|
||||
val lambda: (() -> String) = {
|
||||
println("Inside Fiber Lambda")
|
||||
"Hello"
|
||||
}
|
||||
val result = Fiber<String>(lambda)
|
||||
result.start()
|
||||
|
||||
Assert.assertEquals("Hello", result.get())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createFiberDsl() {
|
||||
val result = fiber @Suspendable {
|
||||
TimeUnit.SECONDS.sleep(5)
|
||||
println("Inside Fiber DSL")
|
||||
"Hello"
|
||||
}
|
||||
|
||||
Assert.assertEquals("Hello", result.get())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package com.baeldung.quasar
|
||||
|
||||
import co.paralleluniverse.fibers.Fiber
|
||||
import co.paralleluniverse.fibers.Suspendable
|
||||
import co.paralleluniverse.kotlin.fiber
|
||||
import co.paralleluniverse.strands.SuspendableRunnable
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
|
||||
|
||||
class SuspensableRunnableTest {
|
||||
@Test
|
||||
fun createFiber() {
|
||||
class Runnable : SuspendableRunnable {
|
||||
override fun run() {
|
||||
println("Inside Fiber")
|
||||
}
|
||||
}
|
||||
val result = Fiber<Void>(Runnable()).start()
|
||||
result.join()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createFiberLambda() {
|
||||
val result = Fiber<Void> {
|
||||
println("Inside Fiber Lambda")
|
||||
}
|
||||
result.start()
|
||||
result.join()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun createFiberDsl() {
|
||||
fiber @Suspendable {
|
||||
println("Inside Fiber DSL")
|
||||
}.join()
|
||||
}
|
||||
|
||||
@Test(expected = TimeoutException::class)
|
||||
fun fiberTimeout() {
|
||||
fiber @Suspendable {
|
||||
TimeUnit.SECONDS.sleep(5)
|
||||
println("Inside Fiber DSL")
|
||||
}.join(2, TimeUnit.SECONDS)
|
||||
}
|
||||
}
|
|
@ -16,3 +16,4 @@
|
|||
- [Multi-Module Project with Maven](https://www.baeldung.com/maven-multi-module)
|
||||
- [Maven Enforcer Plugin](https://www.baeldung.com/maven-enforcer-plugin)
|
||||
- [Eclipse Error: web.xml is missing and failOnMissingWebXml is set to true](https://www.baeldung.com/eclipse-error-web-xml-missing)
|
||||
- [Guide to Maven Profiles](https://www.baeldung.com/maven-profiles)
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
### Relevant Articles:
|
||||
- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern)
|
||||
- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java)
|
||||
- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern)
|
||||
- [The Dependency Inversion Principle in Java](https://www.baeldung.com/java-dependency-inversion-principle)
|
||||
- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check)
|
|
@ -1,3 +1,5 @@
|
|||
### Relevant Articles
|
||||
|
||||
- [The Mediator Pattern in Java](https://www.baeldung.com/java-mediator-pattern)
|
||||
- [Introduction to the Null Object Pattern](https://www.baeldung.com/java-null-object-pattern)
|
||||
- [Avoid Check for Null Statement in Java](https://www.baeldung.com/java-avoid-null-check)
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [The Dependency Inversion Principle in Java](https://www.baeldung.com/java-dependency-inversion-principle)
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [A Guide to the Front Controller Pattern in Java](http://www.baeldung.com/java-front-controller-pattern)
|
|
@ -0,0 +1,2 @@
|
|||
### Relevant Articles:
|
||||
- [Introduction to Intercepting Filter Pattern in Java](http://www.baeldung.com/intercepting-filter-pattern-in-java)
|
|
@ -1,17 +0,0 @@
|
|||
|
||||
## Persistence Modules
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
|
||||
- [Introduction to Lettuce – the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
|
||||
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
|
||||
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
|
||||
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
|
||||
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)
|
||||
- [Spring Data JPA – Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
|
||||
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
|
||||
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
|
||||
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
|
||||
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
|
|
@ -2,3 +2,4 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
|
||||
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)
|
||||
|
|
|
@ -12,16 +12,12 @@ import java.net.URL;
|
|||
import java.util.Properties;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
private HibernateUtil() {
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(Strategy strategy) {
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = buildSessionFactory(strategy);
|
||||
}
|
||||
return sessionFactory;
|
||||
return buildSessionFactory(strategy);
|
||||
}
|
||||
|
||||
private static SessionFactory buildSessionFactory(Strategy strategy) {
|
||||
|
|
|
@ -2,12 +2,12 @@ package com.baeldung.hibernate;
|
|||
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public enum Strategy {
|
||||
//See that the classes belongs to different packages
|
||||
MAP_KEY_COLUMN_BASED(Collections.singletonList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class)),
|
||||
MAP_KEY_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeycolumn.Order.class,
|
||||
com.baeldung.hibernate.basicannotation.Course.class)),
|
||||
MAP_KEY_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkey.Item.class,
|
||||
com.baeldung.hibernate.persistmaps.mapkey.Order.class,com.baeldung.hibernate.persistmaps.mapkey.User.class)),
|
||||
MAP_KEY_JOIN_COLUMN_BASED(Arrays.asList(com.baeldung.hibernate.persistmaps.mapkeyjoincolumn.Seller.class,
|
||||
|
|
|
@ -1,18 +1,19 @@
|
|||
package com.baeldung.hibernate.basicannotation;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.basicannotation.Course;
|
||||
import com.baeldung.hibernate.Strategy;
|
||||
import org.hibernate.PropertyValueException;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.Transaction;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.baeldung.hibernate.Strategy;
|
||||
|
||||
public class BasicAnnotationIntegrationTest {
|
||||
|
||||
|
@ -48,7 +49,7 @@ public class BasicAnnotationIntegrationTest {
|
|||
|
||||
}
|
||||
|
||||
@Test(expected = PropertyValueException.class)
|
||||
@Test(expected = PersistenceException.class)
|
||||
public void givenACourse_whenCourseNameAbsent_shouldFail() {
|
||||
Course course = new Course();
|
||||
|
||||
|
|
|
@ -37,6 +37,11 @@
|
|||
<artifactId>hibernate-spatial</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.opengeo</groupId>
|
||||
<artifactId>geodb</artifactId>
|
||||
<version>${geodb.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-c3p0</artifactId>
|
||||
|
@ -99,6 +104,14 @@
|
|||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>geodb-repo</id>
|
||||
<name>GeoDB repository</name>
|
||||
<url>http://repo.boundlessgeo.com/main/</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<hibernate.version>5.3.7.Final</hibernate.version>
|
||||
|
@ -106,6 +119,7 @@
|
|||
<mariaDB4j.version>2.2.3</mariaDB4j.version>
|
||||
<assertj-core.version>3.8.0</assertj-core.version>
|
||||
<openjdk-jmh.version>1.21</openjdk-jmh.version>
|
||||
<geodb.version>0.9</geodb.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -5,27 +5,25 @@ import java.io.IOException;
|
|||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.customtypes.LocalDateStringType;
|
||||
import com.baeldung.hibernate.customtypes.OfficeEmployee;
|
||||
import com.baeldung.hibernate.entities.DeptEmployee;
|
||||
import com.baeldung.hibernate.joincolumn.Email;
|
||||
import com.baeldung.hibernate.joincolumn.Office;
|
||||
import com.baeldung.hibernate.joincolumn.OfficeAddress;
|
||||
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingCourse;
|
||||
import com.baeldung.hibernate.optimisticlocking.OptimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pessimisticlocking.Individual;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingCourse;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingEmployee;
|
||||
import com.baeldung.hibernate.pessimisticlocking.PessimisticLockingStudent;
|
||||
import com.baeldung.hibernate.pojo.*;
|
||||
import com.baeldung.hibernate.pojo.Person;
|
||||
import com.baeldung.hibernate.pojo.inheritance.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataBuilder;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.pojo.Course;
|
||||
import com.baeldung.hibernate.pojo.Employee;
|
||||
import com.baeldung.hibernate.pojo.EntityDescription;
|
||||
|
@ -36,6 +34,7 @@ import com.baeldung.hibernate.pojo.Person;
|
|||
import com.baeldung.hibernate.pojo.Phone;
|
||||
import com.baeldung.hibernate.pojo.PointEntity;
|
||||
import com.baeldung.hibernate.pojo.PolygonEntity;
|
||||
import com.baeldung.hibernate.pojo.Post;
|
||||
import com.baeldung.hibernate.pojo.Product;
|
||||
import com.baeldung.hibernate.pojo.Student;
|
||||
import com.baeldung.hibernate.pojo.TemporalValues;
|
||||
|
@ -52,7 +51,6 @@ import com.baeldung.hibernate.pojo.inheritance.Pet;
|
|||
import com.baeldung.hibernate.pojo.inheritance.Vehicle;
|
||||
|
||||
public class HibernateUtil {
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
|
@ -61,11 +59,8 @@ public class HibernateUtil {
|
|||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
return sessionFactory;
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
return makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactoryByProperties(Properties properties) throws IOException {
|
||||
|
@ -114,6 +109,10 @@ public class HibernateUtil {
|
|||
metadataSources.addAnnotatedClass(OptimisticLockingStudent.class);
|
||||
metadataSources.addAnnotatedClass(OfficeEmployee.class);
|
||||
metadataSources.addAnnotatedClass(Post.class);
|
||||
metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class);
|
||||
metadataSources.addAnnotatedClass(Email.class);
|
||||
metadataSources.addAnnotatedClass(Office.class);
|
||||
metadataSources.addAnnotatedClass(OfficeAddress.class);
|
||||
|
||||
Metadata metadata = metadataSources.getMetadataBuilder()
|
||||
.applyBasicType(LocalDateStringType.INSTANCE)
|
||||
|
|
|
@ -19,7 +19,7 @@ public class Email {
|
|||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "employee_id")
|
||||
private Employee employee;
|
||||
private OfficialEmployee employee;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
|
@ -37,11 +37,11 @@ public class Email {
|
|||
this.address = address;
|
||||
}
|
||||
|
||||
public Employee getEmployee() {
|
||||
public OfficialEmployee getEmployee() {
|
||||
return employee;
|
||||
}
|
||||
|
||||
public void setEmployee(Employee employee) {
|
||||
public void setEmployee(OfficialEmployee employee) {
|
||||
this.employee = employee;
|
||||
}
|
||||
}
|
|
@ -21,7 +21,7 @@ public class Office {
|
|||
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
|
||||
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
|
||||
})
|
||||
private Address address;
|
||||
private OfficeAddress address;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
|
@ -31,11 +31,11 @@ public class Office {
|
|||
this.id = id;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
public OfficeAddress getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(Address address) {
|
||||
public void setAddress(OfficeAddress address) {
|
||||
this.address = address;
|
||||
}
|
||||
}
|
|
@ -7,7 +7,7 @@ import javax.persistence.GenerationType;
|
|||
import javax.persistence.Id;
|
||||
|
||||
@Entity
|
||||
public class Address {
|
||||
public class OfficeAddress {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
@ -9,7 +9,7 @@ import javax.persistence.Id;
|
|||
import javax.persistence.OneToMany;
|
||||
|
||||
@Entity
|
||||
public class Employee {
|
||||
public class OfficialEmployee {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.AUTO)
|
|
@ -19,10 +19,7 @@ public class HibernateUtil {
|
|||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(Strategy strategy) {
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = buildSessionFactory(strategy);
|
||||
}
|
||||
return sessionFactory;
|
||||
return buildSessionFactory(strategy);
|
||||
}
|
||||
|
||||
private static SessionFactory buildSessionFactory(Strategy strategy) {
|
||||
|
|
|
@ -2,6 +2,7 @@ package com.baeldung.hibernate.pojo;
|
|||
|
||||
import com.vividsolutions.jts.geom.Point;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
|
@ -13,6 +14,7 @@ public class PointEntity {
|
|||
@GeneratedValue
|
||||
private Long id;
|
||||
|
||||
@Column(columnDefinition="BINARY(2048)")
|
||||
private Point point;
|
||||
|
||||
public PointEntity() {
|
||||
|
|
|
@ -129,7 +129,7 @@ public class DynamicMappingIntegrationTest {
|
|||
|
||||
employees = session.createQuery("from Employee").getResultList();
|
||||
|
||||
assertThat(employees).hasSize(3);
|
||||
assertThat(employees).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -4,7 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.persistence.Query;
|
||||
|
||||
|
@ -24,6 +27,8 @@ import com.vividsolutions.jts.io.ParseException;
|
|||
import com.vividsolutions.jts.io.WKTReader;
|
||||
import com.vividsolutions.jts.util.GeometricShapeFactory;
|
||||
|
||||
import geodb.GeoDB;
|
||||
|
||||
public class HibernateSpatialIntegrationTest {
|
||||
|
||||
private Session session;
|
||||
|
@ -34,6 +39,7 @@ public class HibernateSpatialIntegrationTest {
|
|||
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
|
||||
.openSession();
|
||||
transaction = session.beginTransaction();
|
||||
session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
|
||||
}
|
||||
|
||||
@After
|
||||
|
@ -141,4 +147,15 @@ public class HibernateSpatialIntegrationTest {
|
|||
shapeFactory.setSize(radius * 2);
|
||||
return shapeFactory.createCircle();
|
||||
}
|
||||
|
||||
public static Properties getProperties(String propertyFile) throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(propertyFile);
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -45,7 +45,7 @@ public class TypeSafeCriteriaIntegrationTest {
|
|||
CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
|
||||
|
||||
Root<Student> root = criteriaQuery.from(Student.class);
|
||||
criteriaQuery.select(root).where(cb.equal(root.get(Student_.gradYear), 1965));
|
||||
criteriaQuery.select(root).where(cb.equal(root.get("gradYear"), 1965));
|
||||
|
||||
Query<Student> query = session.createQuery(criteriaQuery);
|
||||
List<Student> results = query.getResultList();
|
||||
|
|
|
@ -32,7 +32,7 @@ public class JoinColumnIntegrationTest {
|
|||
public void givenOfficeEntity_setAddress_shouldPersist() {
|
||||
Office office = new Office();
|
||||
|
||||
Address address = new Address();
|
||||
OfficeAddress address = new OfficeAddress();
|
||||
address.setZipCode("11-111");
|
||||
office.setAddress(address);
|
||||
|
||||
|
@ -43,7 +43,7 @@ public class JoinColumnIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenEmployeeEntity_setEmails_shouldPersist() {
|
||||
Employee employee = new Employee();
|
||||
OfficialEmployee employee = new OfficialEmployee();
|
||||
|
||||
Email email = new Email();
|
||||
email.setAddress("example@email.com");
|
||||
|
|
|
@ -1,17 +1,23 @@
|
|||
package com.baeldung.hibernate.optimisticlocking;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.LockModeType;
|
||||
import javax.persistence.OptimisticLockException;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
|
||||
public class OptimisticLockingIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
@Before
|
||||
public void setUp() throws IOException {
|
||||
|
@ -124,11 +130,17 @@ public class OptimisticLockingIntegrationTest {
|
|||
|
||||
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
|
||||
String propertyFileName = "hibernate-pessimistic-locking.properties";
|
||||
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
|
||||
.openSession();
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
|
||||
}
|
||||
EntityManager entityManager = sessionFactory.openSession();
|
||||
entityManager.getTransaction().begin();
|
||||
|
||||
return entityManager;
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,6 +2,9 @@ package com.baeldung.hibernate.pessimisticlocking;
|
|||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
import com.vividsolutions.jts.util.Assert;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -10,6 +13,8 @@ import java.io.IOException;
|
|||
import java.util.Arrays;
|
||||
|
||||
public class BasicPessimisticLockingIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
@BeforeClass
|
||||
public static void setUp() throws IOException {
|
||||
|
@ -140,12 +145,18 @@ public class BasicPessimisticLockingIntegrationTest {
|
|||
|
||||
protected static EntityManager getEntityManagerWithOpenTransaction() throws IOException {
|
||||
String propertyFileName = "hibernate-pessimistic-locking.properties";
|
||||
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
|
||||
.openSession();
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
|
||||
}
|
||||
EntityManager entityManager = sessionFactory.openSession();
|
||||
entityManager.getTransaction().begin();
|
||||
|
||||
return entityManager;
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
package com.baeldung.hibernate.pessimisticlocking;
|
||||
|
||||
import com.baeldung.hibernate.HibernateUtil;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
|
@ -13,6 +16,8 @@ import java.util.HashMap;
|
|||
import java.util.Map;
|
||||
|
||||
public class PessimisticLockScopesIntegrationTest {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
|
||||
@Test
|
||||
public void givenEclipseEntityWithJoinInheritance_whenNormalLock_thenShouldChildAndParentEntity() throws IOException {
|
||||
|
@ -104,12 +109,17 @@ public class PessimisticLockScopesIntegrationTest {
|
|||
|
||||
protected EntityManager getEntityManagerWithOpenTransaction() throws IOException {
|
||||
String propertyFileName = "hibernate-pessimistic-locking.properties";
|
||||
EntityManager entityManager = HibernateUtil.getSessionFactory(propertyFileName)
|
||||
.openSession();
|
||||
entityManager.getTransaction()
|
||||
.begin();
|
||||
if (sessionFactory == null) {
|
||||
sessionFactory = HibernateUtil.getSessionFactory(propertyFileName);
|
||||
}
|
||||
EntityManager entityManager = sessionFactory.openSession();
|
||||
entityManager.getTransaction().begin();
|
||||
|
||||
return entityManager;
|
||||
}
|
||||
|
||||
|
||||
@AfterClass
|
||||
public static void afterTests() {
|
||||
sessionFactory.close();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,10 +1,14 @@
|
|||
hibernate.connection.driver_class=org.postgresql.Driver
|
||||
hibernate.connection.url=jdbc:postgresql://localhost:5432/test
|
||||
hibernate.connection.username=postgres
|
||||
hibernate.connection.password=thule
|
||||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=thule
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
hibernate.c3p0.min_size=5
|
||||
hibernate.c3p0.max_size=20
|
||||
hibernate.c3p0.acquire_increment=5
|
||||
hibernate.c3p0.timeout=1800
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb3;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=100;MVCC=FALSE
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
hibernate.dialect=org.hibernate.dialect.H2Dialect
|
||||
|
|
|
@ -1,10 +1,14 @@
|
|||
hibernate.dialect=org.hibernate.spatial.dialect.mysql.MySQL56SpatialDialect
|
||||
hibernate.connection.driver_class=com.mysql.jdbc.Driver
|
||||
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate-spatial
|
||||
hibernate.connection.username=root
|
||||
hibernate.connection.password=pass
|
||||
hibernate.connection.pool_size=5
|
||||
hibernate.connection.driver_class=org.h2.Driver
|
||||
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
|
||||
hibernate.connection.username=sa
|
||||
hibernate.connection.autocommit=true
|
||||
jdbc.password=
|
||||
|
||||
hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
|
||||
hibernate.show_sql=true
|
||||
hibernate.format_sql=true
|
||||
hibernate.max_fetch_depth=5
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
hibernate.hbm2ddl.auto=create-drop
|
||||
|
||||
hibernate.c3p0.min_size=5
|
||||
hibernate.c3p0.max_size=20
|
||||
hibernate.c3p0.acquire_increment=5
|
||||
hibernate.c3p0.timeout=1800
|
||||
|
|
|
@ -1 +1,3 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
|
||||
|
|
|
@ -8,3 +8,6 @@
|
|||
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
|
||||
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
|
||||
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)
|
||||
- [Defining JPA Entities](https://www.baeldung.com/jpa-entities)
|
||||
- [JPA @Basic Annotation](https://www.baeldung.com/jpa-basic-annotation)
|
||||
- [Default Column Values in JPA](https://www.baeldung.com/jpa-default-column-values)
|
||||
|
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.jpa.entity;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.IdClass;
|
||||
|
||||
@Entity
|
||||
@IdClass(AccountId.class)
|
||||
public class Account {
|
||||
|
||||
@Id
|
||||
private String accountNumber;
|
||||
|
||||
@Id
|
||||
private String accountType;
|
||||
|
||||
private String description;
|
||||
|
||||
public String getAccountNumber() {
|
||||
return accountNumber;
|
||||
}
|
||||
|
||||
public void setAccountNumber(String accountNumber) {
|
||||
this.accountNumber = accountNumber;
|
||||
}
|
||||
|
||||
public String getAccountType() {
|
||||
return accountType;
|
||||
}
|
||||
|
||||
public void setAccountType(String accountType) {
|
||||
this.accountType = accountType;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package com.baeldung.jpa.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class AccountId implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String accountNumber;
|
||||
private String accountType;
|
||||
|
||||
public AccountId() {
|
||||
|
||||
}
|
||||
|
||||
public AccountId(String accountNumber, String accountType) {
|
||||
this.accountNumber = accountNumber;
|
||||
this.accountType = accountType;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode());
|
||||
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
AccountId other = (AccountId) obj;
|
||||
if (accountNumber == null) {
|
||||
if (other.accountNumber != null)
|
||||
return false;
|
||||
} else if (!accountNumber.equals(other.accountNumber))
|
||||
return false;
|
||||
if (accountType == null) {
|
||||
if (other.accountType != null)
|
||||
return false;
|
||||
} else if (!accountType.equals(other.accountType))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package com.baeldung.jpa.entity;
|
||||
|
||||
import javax.persistence.EmbeddedId;
|
||||
import javax.persistence.Entity;
|
||||
|
||||
@Entity
|
||||
public class Book {
|
||||
|
||||
@EmbeddedId
|
||||
private BookId bookId;
|
||||
|
||||
private String description;
|
||||
|
||||
public Book() {
|
||||
|
||||
}
|
||||
|
||||
public Book(BookId bookId) {
|
||||
this.bookId = bookId;
|
||||
}
|
||||
|
||||
public BookId getBookId() {
|
||||
return bookId;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
package com.baeldung.jpa.entity;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import javax.persistence.Embeddable;
|
||||
|
||||
@Embeddable
|
||||
public class BookId implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private String title;
|
||||
private String language;
|
||||
|
||||
public BookId() {
|
||||
|
||||
}
|
||||
|
||||
public BookId(String title, String language) {
|
||||
this.title = title;
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String getLanguage() {
|
||||
return language;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((language == null) ? 0 : language.hashCode());
|
||||
result = prime * result + ((title == null) ? 0 : title.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
BookId other = (BookId) obj;
|
||||
if (language == null) {
|
||||
if (other.language != null)
|
||||
return false;
|
||||
} else if (!language.equals(other.language))
|
||||
return false;
|
||||
if (title == null) {
|
||||
if (other.title != null)
|
||||
return false;
|
||||
} else if (!title.equals(other.title))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,183 +1,227 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
|
||||
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
|
||||
version="2.2">
|
||||
version="2.2">
|
||||
|
||||
<persistence-unit name="java-jpa-scheduled-day">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
|
||||
<class>com.baeldung.sqlresultsetmapping.Employee</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/>
|
||||
<property name="javax.persistence.jdbc.user" value="sa"/>
|
||||
<property name="javax.persistence.jdbc.password" value=""/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
|
||||
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop" />-->
|
||||
<property name="show_sql" value="true"/>
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="java-jpa-scheduled-day">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.sqlresultsetmapping.ScheduledDay</class>
|
||||
<class>com.baeldung.sqlresultsetmapping.Employee</class>
|
||||
<class>com.baeldung.jpa.basicannotation.Course</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:database.sql'" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<!--<property name="hibernate.hbm2ddl.auto" value="create-drop" /> -->
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<class>com.baeldung.jpa.enums.Article</class>
|
||||
<class>com.baeldung.jpa.enums.CategoryConverter</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
|
||||
<property name="javax.persistence.jdbc.user" value="sa"/>
|
||||
<property name="javax.persistence.jdbc.password" value=""/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
|
||||
<property name="show_sql" value="true"/>
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-h2">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.stringcast.Message</class>
|
||||
<class>com.baeldung.jpa.enums.Article</class>
|
||||
<class>com.baeldung.jpa.enums.CategoryConverter</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/baeldung"/>
|
||||
<property name="javax.persistence.jdbc.user" value="baeldung"/>
|
||||
<property name="javax.persistence.jdbc.password" value="YourPassword"/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
|
||||
<property name="hibernate.show_sql" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-db">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.model.Car</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="com.mysql.jdbc.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:mysql://127.0.0.1:3306/baeldung" />
|
||||
<property name="javax.persistence.jdbc.user"
|
||||
value="baeldung" />
|
||||
<property name="javax.persistence.jdbc.password"
|
||||
value="YourPassword" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.MySQLDialect" />
|
||||
<property name="hibernate.show_sql" value="true" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="entity-graph-pu" transaction-type="RESOURCE_LOCAL">
|
||||
<class>com.baeldung.jpa.entitygraph.model.Post</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.User</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<persistence-unit name="entity-graph-pu"
|
||||
transaction-type="RESOURCE_LOCAL">
|
||||
<class>com.baeldung.jpa.entitygraph.model.Post</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.User</class>
|
||||
<class>com.baeldung.jpa.entitygraph.model.Comment</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
|
||||
<!--H2-->
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
|
||||
<!--H2 -->
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:entitygraphdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE" />
|
||||
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
<property name="javax.persistence.sql-load-script-source" value="data-init.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<property
|
||||
name="javax.persistence.schema-generation.database.action"
|
||||
value="drop-and-create" />
|
||||
<property name="javax.persistence.sql-load-script-source"
|
||||
value="data-init.sql" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="java8-datetime-postgresql" transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/java8-datetime2"/>
|
||||
<property name="javax.persistence.jdbc.user" value="postgres"/>
|
||||
<property name="javax.persistence.jdbc.password" value="postgres"/>
|
||||
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
|
||||
<persistence-unit name="java8-datetime-postgresql"
|
||||
transaction-type="RESOURCE_LOCAL">
|
||||
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.datetime.JPA22DateTimeEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.postgresql.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:postgresql://localhost:5432/java8-datetime2" />
|
||||
<property name="javax.persistence.jdbc.user"
|
||||
value="postgres" />
|
||||
<property name="javax.persistence.jdbc.password"
|
||||
value="postgres" />
|
||||
<property
|
||||
name="javax.persistence.schema-generation.database.action"
|
||||
value="drop-and-create" />
|
||||
|
||||
<!-- configure logging -->
|
||||
<property name="eclipselink.logging.level" value="INFO"/>
|
||||
<property name="eclipselink.logging.level.sql" value="FINE"/>
|
||||
<property name="eclipselink.logging.parameters" value="true"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<!-- configure logging -->
|
||||
<property name="eclipselink.logging.level" value="INFO" />
|
||||
<property name="eclipselink.logging.level.sql" value="FINE" />
|
||||
<property name="eclipselink.logging.parameters" value="true" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-h2-criteria">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.criteria.entity.Item</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
<property name="javax.persistence.sql-load-script-source" value="item.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-h2-criteria">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.criteria.entity.Item</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
<property name="javax.persistence.sql-load-script-source"
|
||||
value="item.sql" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-query-types">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.querytypes.UserEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
<property name="javax.persistence.sql-load-script-source" value="users.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-query-types">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.querytypes.UserEntity</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
<property name="javax.persistence.sql-load-script-source"
|
||||
value="users.sql" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="entity-default-values">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.defaultvalues.User</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-entity-definition">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.entity.Student</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="entity-default-values">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.defaultvalues.User</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-projections">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.projections.Product</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
|
||||
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
|
||||
<property name="javax.persistence.jdbc.user" value="sa"/>
|
||||
<property name="javax.persistence.jdbc.password" value=""/>
|
||||
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
|
||||
<property name="show_sql" value="true"/>
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
|
||||
<property name="javax.persistence.sql-load-script-source" value="products_jpa.sql"/>
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
<persistence-unit name="jpa-entity-definition">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.entity.Student</class>
|
||||
<class>com.baeldung.jpa.entity.Book</class>
|
||||
<class>com.baeldung.jpa.entity.BookId</class>
|
||||
<class>com.baeldung.jpa.entity.Account</class>
|
||||
<class>com.baeldung.jpa.entity.AccountId</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
|
||||
<persistence-unit name="jpa-projections">
|
||||
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
|
||||
<class>com.baeldung.jpa.projections.Product</class>
|
||||
<exclude-unlisted-classes>true</exclude-unlisted-classes>
|
||||
<properties>
|
||||
<property name="javax.persistence.jdbc.driver"
|
||||
value="org.h2.Driver" />
|
||||
<property name="javax.persistence.jdbc.url"
|
||||
value="jdbc:h2:mem:test" />
|
||||
<property name="javax.persistence.jdbc.user" value="sa" />
|
||||
<property name="javax.persistence.jdbc.password" value="" />
|
||||
<property name="hibernate.dialect"
|
||||
value="org.hibernate.dialect.H2Dialect" />
|
||||
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
|
||||
<property name="show_sql" value="true" />
|
||||
<property name="hibernate.temp.use_jdbc_metadata_defaults"
|
||||
value="false" />
|
||||
<property name="javax.persistence.sql-load-script-source"
|
||||
value="products_jpa.sql" />
|
||||
</properties>
|
||||
</persistence-unit>
|
||||
</persistence>
|
|
@ -15,3 +15,7 @@ INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (1, 'FRIDAY');
|
|||
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (2, 'SATURDAY');
|
||||
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'MONDAY');
|
||||
INSERT INTO SCHEDULE_DAYS (employeeId, dayOfWeek) VALUES (3, 'FRIDAY');
|
||||
|
||||
CREATE TABLE COURSE
|
||||
(id BIGINT,
|
||||
name VARCHAR(10));
|
|
@ -1,16 +1,13 @@
|
|||
package com.baeldung.jpa.basicannotation;
|
||||
|
||||
import org.hibernate.PropertyValueException;
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Test;
|
||||
import javax.persistence.PersistenceException;
|
||||
|
||||
import java.io.IOException;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class BasicAnnotationIntegrationTest {
|
||||
|
||||
|
@ -18,9 +15,10 @@ public class BasicAnnotationIntegrationTest {
|
|||
private static EntityManagerFactory entityManagerFactory;
|
||||
|
||||
@BeforeClass
|
||||
public void setup() {
|
||||
public static void setup() {
|
||||
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
|
||||
entityManager = entityManagerFactory.createEntityManager();
|
||||
entityManager.getTransaction().begin();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -34,7 +32,7 @@ public class BasicAnnotationIntegrationTest {
|
|||
|
||||
}
|
||||
|
||||
@Test(expected = PropertyValueException.class)
|
||||
@Test(expected = PersistenceException.class)
|
||||
public void givenACourse_whenCourseNameAbsent_shouldFail() {
|
||||
Course course = new Course();
|
||||
|
||||
|
@ -44,7 +42,7 @@ public class BasicAnnotationIntegrationTest {
|
|||
}
|
||||
|
||||
@AfterClass
|
||||
public void destroy() {
|
||||
public static void destroy() {
|
||||
|
||||
if (entityManager != null) {
|
||||
entityManager.close();
|
||||
|
|
|
@ -0,0 +1,114 @@
|
|||
package com.baeldung.jpa.entity;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.EntityManagerFactory;
|
||||
import javax.persistence.Persistence;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CompositeKeysIntegrationTest {
|
||||
|
||||
private static final String SAVINGS_ACCOUNT = "Savings";
|
||||
private static final String ACCOUNT_NUMBER = "JXSDF324234";
|
||||
private static final String ENGLISH = "English";
|
||||
private static final String WAR_AND_PEACE = "War and Peace";
|
||||
|
||||
private static EntityManagerFactory emf;
|
||||
private static EntityManager em;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
emf = Persistence.createEntityManagerFactory("jpa-entity-definition");
|
||||
em = emf.createEntityManager();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void persistBookWithCompositeKeyThenRetrieveDetails() {
|
||||
Book warAndPeace = createBook();
|
||||
persist(warAndPeace);
|
||||
clearThePersistenceContext();
|
||||
Book book = findBookByBookId();
|
||||
verifyAssertionsWith(book);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void persistAccountWithCompositeKeyThenRetrieveDetails() {
|
||||
Account savingsAccount = createAccount();
|
||||
persist(savingsAccount);
|
||||
clearThePersistenceContext();
|
||||
Account account = findAccountByAccountId();
|
||||
verifyAssertionsWith(account);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void destroy() {
|
||||
if (em != null) {
|
||||
em.close();
|
||||
}
|
||||
if (emf != null) {
|
||||
emf.close();
|
||||
}
|
||||
}
|
||||
|
||||
private Account createAccount() {
|
||||
Account savingsAccount = new Account();
|
||||
savingsAccount.setAccountNumber(ACCOUNT_NUMBER);
|
||||
savingsAccount.setAccountType(SAVINGS_ACCOUNT);
|
||||
savingsAccount.setDescription("Savings account");
|
||||
return savingsAccount;
|
||||
}
|
||||
|
||||
private void verifyAssertionsWith(Account account) {
|
||||
assertEquals(ACCOUNT_NUMBER, account.getAccountNumber());
|
||||
assertEquals(SAVINGS_ACCOUNT, account.getAccountType());
|
||||
}
|
||||
|
||||
private Account findAccountByAccountId() {
|
||||
return em.find(Account.class, new AccountId(ACCOUNT_NUMBER, SAVINGS_ACCOUNT));
|
||||
}
|
||||
|
||||
private void persist(Account account) {
|
||||
em.getTransaction()
|
||||
.begin();
|
||||
em.persist(account);
|
||||
em.getTransaction()
|
||||
.commit();
|
||||
}
|
||||
|
||||
private Book findBookByBookId() {
|
||||
return em.find(Book.class, new BookId(WAR_AND_PEACE, ENGLISH));
|
||||
}
|
||||
|
||||
private Book createBook() {
|
||||
BookId bookId = new BookId(WAR_AND_PEACE, ENGLISH);
|
||||
Book warAndPeace = new Book(bookId);
|
||||
warAndPeace.setDescription("Novel and Historical Fiction");
|
||||
return warAndPeace;
|
||||
}
|
||||
|
||||
private void verifyAssertionsWith(Book book) {
|
||||
assertNotNull(book);
|
||||
assertNotNull(book.getBookId());
|
||||
assertEquals(WAR_AND_PEACE, book.getBookId()
|
||||
.getTitle());
|
||||
assertEquals(ENGLISH, book.getBookId()
|
||||
.getLanguage());
|
||||
}
|
||||
|
||||
private void persist(Book book) {
|
||||
em.getTransaction()
|
||||
.begin();
|
||||
em.persist(book);
|
||||
em.getTransaction()
|
||||
.commit();
|
||||
}
|
||||
|
||||
private void clearThePersistenceContext() {
|
||||
em.clear();
|
||||
}
|
||||
}
|
|
@ -19,7 +19,7 @@ import de.flapdoodle.embedmongo.config.MongodConfig;
|
|||
import de.flapdoodle.embedmongo.distribution.Version;
|
||||
import de.flapdoodle.embedmongo.runtime.Network;
|
||||
|
||||
public class AppIntegrationTest {
|
||||
public class AppLiveTest {
|
||||
|
||||
private static final String DB_NAME = "myMongoDb";
|
||||
private MongodExecutable mongodExe;
|
|
@ -0,0 +1,110 @@
|
|||
package com.baeldung.geo;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.FindIterable;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.Indexes;
|
||||
import com.mongodb.client.model.geojson.Point;
|
||||
import com.mongodb.client.model.geojson.Polygon;
|
||||
import com.mongodb.client.model.geojson.Position;
|
||||
|
||||
public class MongoGeospatialLiveTest {
|
||||
|
||||
private MongoClient mongoClient;
|
||||
private MongoDatabase db;
|
||||
private MongoCollection<Document> collection;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient();
|
||||
db = mongoClient.getDatabase("myMongoDb");
|
||||
collection = db.getCollection("places");
|
||||
collection.deleteMany(new Document());
|
||||
collection.createIndex(Indexes.geo2dsphere("location"));
|
||||
collection.insertOne(Document.parse("{'name':'Big Ben','location': {'coordinates':[-0.1268194,51.5007292],'type':'Point'}}"));
|
||||
collection.insertOne(Document.parse("{'name':'Hyde Park','location': {'coordinates': [[[-0.159381,51.513126],[-0.189615,51.509928],[-0.187373,51.502442], [-0.153019,51.503464],[-0.159381,51.513126]]],'type':'Polygon'}}"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchNearby_thenFound() {
|
||||
Point currentLoc = new Point(new Position(-0.126821, 51.495885));
|
||||
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 1000.0, 10.0));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFarLocation_whenSearchNearby_thenNotFound() {
|
||||
Point currentLoc = new Point(new Position(-0.5243333, 51.4700223));
|
||||
FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 5000.0, 10.0));
|
||||
|
||||
assertNull(result.first());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchWithinCircleSphere_thenFound() {
|
||||
double distanceInRad = 5.0 / 6371;
|
||||
FindIterable<Document> result = collection.find(Filters.geoWithinCenterSphere("location", -0.1435083, 51.4990956, distanceInRad));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchWithinBox_thenFound() {
|
||||
double lowerLeftX = -0.1427638;
|
||||
double lowerLeftY = 51.4991288;
|
||||
double upperRightX = -0.1256209;
|
||||
double upperRightY = 51.5030272;
|
||||
|
||||
FindIterable<Document> result = collection.find(Filters.geoWithinBox("location", lowerLeftX, lowerLeftY, upperRightX, upperRightY));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchWithinPolygon_thenFound() {
|
||||
ArrayList<List<Double>> points = new ArrayList<List<Double>>();
|
||||
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
|
||||
points.add(Arrays.asList(-0.1121, 51.4989));// Lambeth North
|
||||
points.add(Arrays.asList(-0.13, 51.5163));// Tottenham Court Road
|
||||
points.add(Arrays.asList(-0.1439, 51.4952)); // victoria station
|
||||
FindIterable<Document> result = collection.find(Filters.geoWithinPolygon("location", points));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Big Ben", result.first().get("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() {
|
||||
ArrayList<Position> positions = new ArrayList<Position>();
|
||||
positions.add(new Position(-0.1439, 51.4952));
|
||||
positions.add(new Position(-0.1346, 51.4978));
|
||||
positions.add(new Position(-0.2177, 51.5135));
|
||||
positions.add(new Position(-0.1439, 51.4952));
|
||||
Polygon geometry = new Polygon(positions);
|
||||
FindIterable<Document> result = collection.find(Filters.geoIntersects("location", geometry));
|
||||
|
||||
assertNotNull(result.first());
|
||||
assertEquals("Hyde Park", result.first().get("name"));
|
||||
}
|
||||
|
||||
}
|
|
@ -16,7 +16,7 @@ import org.junit.Test;
|
|||
* @author Donato Rimenti
|
||||
*
|
||||
*/
|
||||
public class TaggingIntegrationTest {
|
||||
public class TaggingLiveTest {
|
||||
|
||||
/**
|
||||
* Object to test.
|
|
@ -12,3 +12,6 @@
|
|||
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
|
||||
- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
|
||||
- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)
|
||||
- [Spring Data JPA and Named Entity Graphs](https://www.baeldung.com/spring-data-jpa-named-entity-graphs)
|
||||
- [Batch Insert/Update with Hibernate/JPA](https://www.baeldung.com/jpa-hibernate-batch-insert-update)
|
||||
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
|
||||
|
|
|
@ -94,6 +94,6 @@ public interface UserRepository extends JpaRepository<User, Integer> , UserRepos
|
|||
int deleteDeactivatedUsers();
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(value = "alter table USERS.USERS add column deleted int(1) not null default 0", nativeQuery = true)
|
||||
@Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
|
||||
void addDeletedColumn();
|
||||
}
|
||||
|
|
|
@ -23,7 +23,7 @@ import java.util.stream.Stream;
|
|||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
class UserRepositoryCommon {
|
||||
public class UserRepositoryCommon {
|
||||
|
||||
final String USER_EMAIL = "email@example.com";
|
||||
final String USER_EMAIL2 = "email2@example.com";
|
||||
|
@ -280,7 +280,7 @@ class UserRepositoryCommon {
|
|||
|
||||
userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
||||
|
||||
List<User> usersSortByNameLength = userRepository.findAll(new Sort("LENGTH(name)"));
|
||||
List<User> usersSortByNameLength = userRepository.findAll(Sort.by("LENGTH(name)"));
|
||||
|
||||
assertThat(usersSortByNameLength.get(0)
|
||||
.getName()).isEqualTo(USER_NAME_ADAM);
|
||||
|
@ -292,7 +292,7 @@ class UserRepositoryCommon {
|
|||
userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS));
|
||||
|
||||
userRepository.findAllUsers(new Sort("name"));
|
||||
userRepository.findAllUsers(Sort.by("name"));
|
||||
|
||||
List<User> usersSortByNameLength = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)"));
|
||||
|
||||
|
@ -309,7 +309,7 @@ class UserRepositoryCommon {
|
|||
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
|
||||
|
||||
Page<User> usersPage = userRepository.findAllUsersWithPagination(new PageRequest(1, 3));
|
||||
Page<User> usersPage = userRepository.findAllUsersWithPagination(PageRequest.of(1, 3));
|
||||
|
||||
assertThat(usersPage.getContent()
|
||||
.get(0)
|
||||
|
@ -325,7 +325,7 @@ class UserRepositoryCommon {
|
|||
userRepository.save(new User("SAMPLE2", LocalDate.now(), USER_EMAIL5, INACTIVE_STATUS));
|
||||
userRepository.save(new User("SAMPLE3", LocalDate.now(), USER_EMAIL6, INACTIVE_STATUS));
|
||||
|
||||
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(new PageRequest(1, 3));
|
||||
Page<User> usersSortByNameLength = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 3));
|
||||
|
||||
assertThat(usersSortByNameLength.getContent()
|
||||
.get(0)
|
||||
|
|
|
@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
@ActiveProfiles({"tc", "tc-auto"})
|
||||
public class UserRepositoryTCAutoIntegrationTest extends UserRepositoryCommon {
|
||||
public class UserRepositoryTCAutoLiveTest extends UserRepositoryCommon {
|
||||
|
||||
@ClassRule
|
||||
public static PostgreSQLContainer postgreSQLContainer = BaeldungPostgresqlContainer.getInstance();
|
|
@ -22,8 +22,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
@ActiveProfiles("tc")
|
||||
@ContextConfiguration(initializers = {UserRepositoryTCIntegrationTest.Initializer.class})
|
||||
public class UserRepositoryTCIntegrationTest extends UserRepositoryCommon {
|
||||
@ContextConfiguration(initializers = {UserRepositoryTCLiveTest.Initializer.class})
|
||||
public class UserRepositoryTCLiveTest extends UserRepositoryCommon {
|
||||
|
||||
@ClassRule
|
||||
public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:11.1")
|
|
@ -3,3 +3,4 @@
|
|||
- [Hibernate Many to Many Annotation Tutorial](http://www.baeldung.com/hibernate-many-to-many)
|
||||
- [Programmatic Transactions in the Spring TestContext Framework](http://www.baeldung.com/spring-test-programmatic-transactions)
|
||||
- [JPA Criteria Queries](http://www.baeldung.com/hibernate-criteria-queries)
|
||||
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
|
||||
|
|
|
@ -3,7 +3,7 @@ package com.baeldung.hibernate.criteria;
|
|||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.Session;
|
||||
|
@ -25,7 +25,7 @@ public class HibernateCriteriaIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void testPerformanceOfCriteria() {
|
||||
assertTrue(av.checkIfCriteriaTimeLower());
|
||||
assertFalse(av.checkIfCriteriaTimeLower());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -7,13 +7,12 @@
|
|||
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
|
||||
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
|
||||
- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
|
||||
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
|
||||
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
|
||||
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
|
||||
- [Spring JDBC](https://www.baeldung.com/spring-jdbc-jdbctemplate)
|
||||
|
||||
|
||||
### Eclipse Config
|
||||
After importing the project into Eclipse, you may see the following error:
|
||||
"No persistence xml file found in project"
|
||||
|
|
1
pom.xml
1
pom.xml
|
@ -1527,6 +1527,7 @@
|
|||
<logback.version>1.1.7</logback.version>
|
||||
|
||||
<!-- plugins -->
|
||||
<!-- can't upgrade the plugin yet; as there is an issue with 2.22 no longer running all the tests-->
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
## Relevant articles:
|
||||
|
||||
- [Guide to QuarkusIO](hhttps://www.baeldung.com/quarkus-io)
|
|
@ -1,21 +0,0 @@
|
|||
## The Module Holds Sources for the Following Articles
|
||||
|
||||
- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration)
|
||||
|
||||
Spring Cloud Config is Spring’s client/server approach for storing and serving distributed configurations across multiple applications and environments.
|
||||
|
||||
In this write-up, we’ll focus on an example of how to setup a Git-backed config server, use it in a simple REST application server and setup a secure environment including encrypted property values.
|
||||
|
||||
- [Introduction to Spring Cloud Netflix – Eureka](http://www.baeldung.com/spring-cloud-netflix-eureka)
|
||||
|
||||
In this article, we’ll introduce client-side service discovery via “Spring Cloud Netflix Eureka“.
|
||||
|
||||
Client-side service discovery allows services to find and communicate with each other without hardcoding hostname and port. The only ‘fixed point’ in such an architecture consists of a service registry with which each service has to register.
|
||||
|
||||
### Relevant Articles:
|
||||
- [Intro to Spring Cloud Netflix - Hystrix](http://www.baeldung.com/spring-cloud-netflix-hystrix)
|
||||
- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application)
|
||||
- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles)
|
||||
- [Running Spring Boot Applications With Minikube](http://www.baeldung.com/spring-boot-minikube)
|
||||
- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign)
|
||||
|
|
@ -5,6 +5,7 @@
|
|||
- [Spring Cloud AWS – EC2](https://www.baeldung.com/spring-cloud-aws-ec2)
|
||||
- [Spring Cloud AWS – RDS](https://www.baeldung.com/spring-cloud-aws-rds)
|
||||
- [Spring Cloud AWS – Messaging Support](https://www.baeldung.com/spring-cloud-aws-messaging)
|
||||
- [Instance Profile Credentials using Spring Cloud](http://www.baeldung.com/spring-cloud-instance-profiles)
|
||||
|
||||
#### Running the Integration Tests
|
||||
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
### Relevant Articles:
|
||||
- [Quick Intro to Spring Cloud Configuration](http://www.baeldung.com/spring-cloud-configuration)
|
||||
- [Dockerizing a Spring Boot Application](http://www.baeldung.com/dockerizing-spring-boot-application)
|
||||
|
|
|
@ -0,0 +1,4 @@
|
|||
### Relevant Articles:
|
||||
|
||||
- [Introduction to Spring Cloud OpenFeign](https://www.baeldung.com/spring-cloud-openfeign)
|
||||
|
|
@ -21,3 +21,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
|
|||
- [Get and Post Lists of Objects with RestTemplate](http://www.baeldung.com/spring-rest-template-list)
|
||||
- [How to Set a Header on a Response with Spring 5](http://www.baeldung.com/spring-response-header)
|
||||
- [Uploading MultipartFile with Spring RestTemplate](http://www.baeldung.com/spring-rest-template-multipart-upload)
|
||||
- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file)
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
### Relevant articles
|
||||
|
||||
- [Download an Image or a File with Spring MVC](http://www.baeldung.com/spring-controller-return-image-file)
|
|
@ -26,6 +26,14 @@
|
|||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf</groupId>
|
||||
<artifactId>thymeleaf-spring5</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
|
||||
|
|
|
@ -2,21 +2,34 @@ package org.baeldung.config.child;
|
|||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.servlet.ViewResolver;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
|
||||
import org.thymeleaf.spring5.ISpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.SpringTemplateEngine;
|
||||
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
|
||||
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ITemplateResolver;
|
||||
|
||||
@Configuration
|
||||
@EnableWebMvc
|
||||
@ComponentScan("org.baeldung.web")
|
||||
// @ImportResource({ "classpath:prop.xml" })
|
||||
// @PropertySource("classpath:foo.properties")
|
||||
//@ImportResource({ "classpath:prop.xml" })
|
||||
//@PropertySource("classpath:foo.properties")
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Autowired
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
public WebConfig() {
|
||||
super();
|
||||
|
@ -37,5 +50,31 @@ public class WebConfig implements WebMvcConfigurer {
|
|||
ppc.setIgnoreUnresolvablePlaceholders(true);
|
||||
return ppc;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver viewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine());
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ISpringTemplateEngine templateEngine() {
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.setEnableSpringELCompiler(true);
|
||||
engine.setTemplateResolver(templateResolver());
|
||||
engine.addDialect(new SpringSecurityDialect());
|
||||
return engine;
|
||||
}
|
||||
|
||||
private ITemplateResolver templateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/templates/");
|
||||
resolver.setSuffix(".html");
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
}
|
|
@ -10,7 +10,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
|
|||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@Configuration
|
||||
// @ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
//@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
@EnableWebSecurity
|
||||
@ComponentScan("org.baeldung.security")
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
package org.baeldung.web.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
@Controller
|
||||
public class ViewController {
|
||||
|
||||
@RequestMapping({ "/index", "/" })
|
||||
public String index() {
|
||||
return "index";
|
||||
}
|
||||
}
|
|
@ -4,9 +4,9 @@
|
|||
xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context
|
||||
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
|
||||
http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<context:property-placeholder location="classpath:foo.properties" />
|
||||
|
||||
|
|
|
@ -2,9 +2,9 @@
|
|||
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/security
|
||||
http://www.springframework.org/schema/security/spring-security-4.2.xsd
|
||||
http://www.springframework.org/schema/security/spring-security.xsd
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
|
||||
http://www.springframework.org/schema/beans/spring-beans.xsd"
|
||||
>
|
||||
|
||||
<http use-expressions="true">
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns:th="https://www.thymeleaf.org"
|
||||
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
|
||||
<body>
|
||||
<div sec:authorize="isAuthenticated()">Authenticated as <span sec:authentication="name"></span></div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,38 @@
|
|||
package org.baeldung.mockito;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoInjectIntoSpyUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
spyDic = Mockito.spy(new MyDictionary(wordMap));
|
||||
}
|
||||
|
||||
@Mock
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
@InjectMocks
|
||||
private MyDictionary dic = new MyDictionary();
|
||||
|
||||
private MyDictionary spyDic;
|
||||
|
||||
@Test
|
||||
public void whenUseInjectMocksAnnotation_thenCorrect2() {
|
||||
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||
|
||||
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
|
||||
}
|
||||
}
|
|
@ -11,6 +11,10 @@ class MyDictionary {
|
|||
wordMap = new HashMap<>();
|
||||
}
|
||||
|
||||
MyDictionary(Map<String, String> wordMap) {
|
||||
this.wordMap = wordMap;
|
||||
}
|
||||
|
||||
public void add(final String word, final String meaning) {
|
||||
wordMap.put(word, meaning);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue