Merge branch 'eugenp:master' into master

This commit is contained in:
Ulisses Lima 2022-02-28 10:56:45 -03:00 committed by GitHub
commit 6a9b7f935f
122 changed files with 2580 additions and 562 deletions

View File

@ -1,7 +1,5 @@
package com.baeldung.algorithms.dfs;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class BinaryTree {
@ -124,69 +122,43 @@ public class BinaryTree {
}
}
public void traverseLevelOrder() {
if (root == null) {
return;
}
Queue<Node> nodes = new LinkedList<>();
nodes.add(root);
while (!nodes.isEmpty()) {
Node node = nodes.remove();
System.out.print(" " + node.value);
if (node.left != null) {
nodes.add(node.left);
}
if (node.left != null) {
nodes.add(node.right);
}
}
}
public void traverseInOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack = new Stack<>();
Node current = root;
stack.push(root);
while(! stack.isEmpty()) {
while(current.left != null) {
current = current.left;
stack.push(current);
}
current = stack.pop();
visit(current.value);
if(current.right != null) {
current = current.right;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
Node top = stack.pop();
visit(top.value);
current = top.right;
}
}
public void traversePreOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Node current = root;
Stack<Node> stack = new Stack<>();
Node current;
stack.push(root);
while(! stack.isEmpty()) {
current = stack.pop();
visit(current.value);
if(current.right != null)
stack.push(current.right);
if(current.left != null)
stack.push(current.left);
}
}
}
public void traversePostOrderWithoutRecursion() {
Stack<Node> stack = new Stack<Node>();
Stack<Node> stack = new Stack<>();
Node prev = root;
Node current = root;
Node current;
stack.push(root);
while (!stack.isEmpty()) {
@ -206,14 +178,14 @@ public class BinaryTree {
stack.push(current.left);
}
}
}
}
private void visit(int value) {
System.out.print(" " + value);
}
}
class Node {
private void visit(int value) {
System.out.print(" " + value);
}
static class Node {
int value;
Node left;
Node right;

View File

@ -1,11 +1,11 @@
package com.baeldung.algorithms.dfs;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class BinaryTreeUnitTest {
@Test
@ -13,7 +13,7 @@ public class BinaryTreeUnitTest {
BinaryTree bt = createBinaryTree();
assertTrue(!bt.isEmpty());
assertFalse(bt.isEmpty());
}
@Test
@ -111,14 +111,6 @@ public class BinaryTreeUnitTest {
bt.traversePostOrderWithoutRecursion();
}
@Test
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
BinaryTree bt = createBinaryTree();
bt.traverseLevelOrder();
}
private BinaryTree createBinaryTree() {
BinaryTree bt = new BinaryTree();

View File

@ -8,4 +8,5 @@ This module contains articles about Java 8 core features
- [Java 8 Stream skip() vs limit()](https://www.baeldung.com/java-stream-skip-vs-limit)
- [Guide to Java BiFunction Interface](https://www.baeldung.com/java-bifunction-interface)
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [[<-- Prev]](/core-java-modules/core-java-8)

View File

@ -1,17 +1,24 @@
package com.baeldung.game;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.*;
class RockPaperScissorsGame {
private static Map<Integer, String> movesMap = new HashMap<Integer, String>() {{
put(0, "rock");
put(1, "paper");
put(2, "scissors");
}};
enum Move {
ROCK("rock"),
PAPER("paper"),
SCISSORS("scissors");
private String value;
Move(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
@ -31,7 +38,7 @@ class RockPaperScissorsGame {
break;
}
if (!movesMap.containsValue(playerMove)) {
if (Arrays.stream(Move.values()).noneMatch(x -> x.getValue().equals(playerMove))) {
System.out.println("Your move isn't valid!");
continue;
}
@ -51,15 +58,15 @@ class RockPaperScissorsGame {
}
private static boolean isPlayerWin(String playerMove, String computerMove) {
return playerMove.equals("rock") && computerMove.equals("scissors")
|| (playerMove.equals("scissors") && computerMove.equals("paper"))
|| (playerMove.equals("paper") && computerMove.equals("rock"));
return playerMove.equals(Move.ROCK.value) && computerMove.equals(Move.SCISSORS.value)
|| (playerMove.equals(Move.SCISSORS.value) && computerMove.equals(Move.PAPER.value))
|| (playerMove.equals(Move.PAPER.value) && computerMove.equals(Move.ROCK.value));
}
private static String getComputerMove() {
Random random = new Random();
int randomNumber = random.nextInt(3);
String computerMove = movesMap.get(randomNumber);
String computerMove = Move.values()[randomNumber].getValue();
System.out.println("Computer move: " + computerMove);
return computerMove;
}

View File

@ -7,3 +7,4 @@
- [ArrayList vs. LinkedList vs. HashMap in Java](https://www.baeldung.com/java-arraylist-vs-linkedlist-vs-hashmap)
- [Java Deque vs. Stack](https://www.baeldung.com/java-deque-vs-stack)
- [Collection.toArray(new T[0]) or .toArray(new T[size])](https://www.baeldung.com/java-collection-toarray-methods)
- [Create an Empty Map in Java](https://www.baeldung.com/java-create-empty-map)

View File

@ -15,6 +15,16 @@
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -37,12 +47,23 @@
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.9</maven.compiler.source>
<maven.compiler.target>1.9</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,53 @@
package com.baeldung.entries;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
public class SimpleCustomKeyValue<K, V> implements Map.Entry<K, V> {
private final K key;
private V value;
public SimpleCustomKeyValue(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
return this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SimpleCustomKeyValue<?, ?> that = (SimpleCustomKeyValue<?, ?>) o;
return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(key, value);
}
@Override
public String toString() {
return new StringJoiner(", ", SimpleCustomKeyValue.class.getSimpleName() + "[", "]").add("key=" + key).add("value=" + value).toString();
}
}

View File

@ -0,0 +1,113 @@
package com.baeldung.entries;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.KeyValue;
import org.apache.commons.collections4.keyvalue.DefaultMapEntry;
import org.apache.commons.collections4.keyvalue.UnmodifiableMapEntry;
import org.junit.jupiter.api.Test;
import java.util.AbstractMap;
import java.util.Map;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class EntriesExampleUnitTest {
@Test
public void givenEntries_whenVerifying_thenShouldContainKeyValues() {
AbstractMap.SimpleEntry<String, String> firstEntry = new AbstractMap.SimpleEntry<>("key1", "value1");
AbstractMap.SimpleEntry<String, String> secondEntry = new AbstractMap.SimpleEntry<>("key2", "value2");
AbstractMap.SimpleEntry<String, String> thirdEntry = new AbstractMap.SimpleEntry<>(firstEntry);
thirdEntry.setValue("a different value");
assertThat(Stream.of(firstEntry, secondEntry, thirdEntry))
.extracting("key", "value")
.containsExactly(
tuple("key1", "value1"),
tuple("key2", "value2"),
tuple("key1", "a different value"));
}
@Test
public void givenImmutableEntries_whenVerifying_thenShouldContainKeyValues() {
AbstractMap.SimpleImmutableEntry<String, String> firstEntry = new AbstractMap.SimpleImmutableEntry<>("key1", "value1");
AbstractMap.SimpleImmutableEntry<String, String> secondEntry = new AbstractMap.SimpleImmutableEntry<>("key2", "value2");
AbstractMap.SimpleImmutableEntry<String, String> thirdEntry = new AbstractMap.SimpleImmutableEntry<>(firstEntry);
assertThat(Stream.of(firstEntry, secondEntry, thirdEntry))
.extracting("key", "value")
.containsExactly(
tuple("key1", "value1"),
tuple("key2", "value2"),
tuple("key1", "value1"));
}
@Test
public void givenImmutableEntryUsingJava9_whenVerifying_thenShouldContainKeyValues() {
Map.Entry<String, String> entry = Map.entry("key", "value");
assertThat(entry.getKey())
.isEqualTo("key");
assertThat(entry.getValue())
.isEqualTo("value");
}
@Test
public void givenEntriesWithApacheCommons_whenVerifying_thenShouldContainKeyValues() {
Map.Entry<String, String> firstEntry = new DefaultMapEntry<>("key1", "value1");
KeyValue<String, String> secondEntry = new DefaultMapEntry<>("key2", "value2");
KeyValue<String, String> thirdEntry = new DefaultMapEntry<>(firstEntry);
KeyValue<String, String> fourthEntry = new DefaultMapEntry<>(secondEntry);
firstEntry.setValue("a different value");
assertThat(firstEntry)
.extracting("key", "value")
.containsExactly("key1", "a different value");
assertThat(Stream.of(secondEntry, thirdEntry, fourthEntry))
.extracting("key", "value")
.containsExactly(
tuple("key2", "value2"),
tuple("key1", "value1"),
tuple("key2", "value2"));
}
@Test
public void givenImmutableEntriesWithApacheCommons_whenVerifying_thenShouldContainKeyValues() {
Map.Entry<String, String> firstEntry = new UnmodifiableMapEntry<>("key1", "value1");
KeyValue<String, String> secondEntry = new UnmodifiableMapEntry<>("key2", "value2");
KeyValue<String, String> thirdEntry = new UnmodifiableMapEntry<>(firstEntry);
KeyValue<String, String> fourthEntry = new UnmodifiableMapEntry<>(secondEntry);
assertThat(firstEntry)
.extracting("key", "value")
.containsExactly("key1", "value1");
assertThat(Stream.of(secondEntry, thirdEntry, fourthEntry))
.extracting("key", "value")
.containsExactly(
tuple("key2", "value2"),
tuple("key1", "value1"),
tuple("key2", "value2"));
}
@Test
public void givenImmutableEntriesWithGuava_whenVerifying_thenShouldContainKeyValues() {
Map.Entry<String, String> firstEntry = Maps.immutableEntry("key1", "value1");
Map.Entry<String, String> secondEntry = Maps.immutableEntry("key2", "value2");
assertThat(Stream.of(firstEntry, secondEntry))
.extracting("key", "value")
.containsExactly(
tuple("key1", "value1"),
tuple("key2", "value2"));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.entries;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
class SimpleCustomKeyValueUnitTest {
@Test
public void givenModifiableEntries_whenVerifying_thenShouldContainKeyValues() {
Map.Entry<String, String> firstEntry = new SimpleCustomKeyValue<>("key1", "value1");
Map.Entry<String, String> secondEntry = new SimpleCustomKeyValue<>("key2", "value2");
secondEntry.setValue("different value");
Map<String, String> map = Map.ofEntries(firstEntry, secondEntry);
assertThat(map)
.isEqualTo(ImmutableMap.<String,String>builder()
.put("key1", "value1")
.put("key2", "different value")
.build());
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.exception.variablemightnothavebeeninitialized;
public class VariableMightNotHaveBeenInitialized {
private static int instanceVariableCount;
/**
* Method would not compile if lines 14 and 18 are uncommented.
*/
public static void countEven() {
//uninstantiated
int count;
int[] arr = new int[]{23, 56, 89, 12, 23};
for (int i = 0; i < arr.length; i++) {
if ((arr[i] % 2) == 0) {
// count++;
}
}
// System.out.println("Total Even Numbers : " + count);
}
public static int countEvenUsingInstanceVariable(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if ((arr[i] % 2) == 0) {
instanceVariableCount++;
}
}
return instanceVariableCount;
}
public static int countEvenUsingIfElse(int[] arr, int args) {
int count;
count = args > 0 ? args : 0;
for (int i = 0; i < arr.length; i++) {
if ((arr[i] % 2) == 0) {
count++;
}
}
return count;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.exception.variablemightnothavebeeninitialized;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class VariableMightNotHaveBeenInitializedUnitTest {
@Test
public void usingInstanceVariable_returnCount() {
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
int value = VariableMightNotHaveBeenInitialized.countEvenUsingInstanceVariable(arr);
assertEquals(3, value);
}
@Test
public void usingArgumentsAndIfElse_returnCount() {
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
int value = VariableMightNotHaveBeenInitialized.countEvenUsingIfElse(arr, 2);
assertEquals(5, value);
}
}

View File

@ -0,0 +1,339 @@
package com.baeldung.bytebuffer;
import org.junit.Test;
import java.lang.reflect.Field;
import java.nio.*;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.*;
public class ByteBufferUnitTest {
@Test
public void givenBufferCreation_whenUsingAllocate_thenSuccess() {
ByteBuffer buffer = ByteBuffer.allocate(10);
assertNotNull(buffer);
}
@Test
public void givenBufferCreation_whenUsingAllocateDirect_thenSuccess() {
ByteBuffer buffer = ByteBuffer.allocateDirect(10);
assertNotNull(buffer);
}
@Test
public void givenBufferCreation_whenUsingWrap_thenSuccess() {
byte[] bytes = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
assertNotNull(buffer);
}
@Test
public void givenBufferIndex_whenUsingAllocate_thenInitialIndices() {
// create instance using allocate
ByteBuffer buffer = ByteBuffer.allocate(10);
// get index
int position = buffer.position();
int limit = buffer.limit();
int capacity = buffer.capacity();
// assert
assertEquals(0, position);
assertEquals(10, limit);
assertEquals(10, capacity);
}
@Test
public void givenBufferIndex_whenChangingPositionAndLimit_thenSuccess() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
// change index
buffer.position(2);
buffer.limit(5);
// assert
assertIndex(buffer, -1, 2, 5, 10);
}
@Test
public void givenBufferIndex_whenUsingWrap_thenInitialIndices() {
// create instance
byte[] bytes = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
// assert
assertIndex(buffer, -1, 0, 10, 10);
}
@Test
public void givenBufferIndex_whenUsingWrapWithOffsetAndLength_thenInitialIndices() {
// create instance
byte[] bytes = new byte[10];
ByteBuffer buffer = ByteBuffer.wrap(bytes, 2, 6);
// assert
assertIndex(buffer, -1, 2, 8, 10);
}
@Test
public void givenBufferIndex_whenUsingMarkAndReset_thenOK() {
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
buffer.position(2);
assertIndex(buffer, -1, 2, 10, 10);
buffer.mark();
assertIndex(buffer, 2, 2, 10, 10);
buffer.position(5);
assertIndex(buffer, 2, 5, 10, 10);
buffer.reset();
assertIndex(buffer, 2, 2, 10, 10);
}
@Test
public void givenBufferIndex_whenUsingClear_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// clear
buffer.clear();
assertIndex(buffer, -1, 0, 10, 10);
}
@Test
public void givenBufferIndex_whenUsingFlip_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// flip
buffer.flip();
assertIndex(buffer, -1, 0, 5, 10);
}
@Test
public void givenBufferIndex_whenUsingRewind_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// rewind
buffer.rewind();
assertIndex(buffer, -1, 0, 8, 10);
}
@Test
public void givenBufferIndex_whenUsingCompact_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// compact
buffer.compact();
assertIndex(buffer, -1, 3, 10, 10);
}
@Test
public void givenBufferIndex_whenUsingRemain_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
// change index
buffer.position(2);
buffer.limit(8);
// remain
boolean flag = buffer.hasRemaining();
int remaining = buffer.remaining();
// assert
assertTrue(flag);
assertEquals(6, remaining);
}
@Test(expected = BufferUnderflowException.class)
public void givenNotEnoughRemaining_WhenCallingGetInt_thenBufferUnderflowException() {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.getInt();
}
@Test(expected = BufferOverflowException.class)
public void givenNotEnoughRemaining_WhenCallingPutInt_thenBufferOverflowException() {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(10);
}
@Test
public void givenBufferView_whenUsingDuplicate_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// view
ByteBuffer view = buffer.duplicate();
assertIndex(view, 2, 5, 8, 10);
}
@Test
public void givenBufferView_whenUsingSlice_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// view
ByteBuffer view = buffer.slice();
assertIndex(view, -1, 0, 3, 3);
}
@Test
public void givenBufferView_whenUsingAsReaOnlyBuffer_thenOK() {
// create instance
ByteBuffer buffer = ByteBuffer.allocate(10);
assertIndex(buffer, -1, 0, 10, 10);
// change index
buffer.position(2);
buffer.mark();
buffer.position(5);
buffer.limit(8);
assertIndex(buffer, 2, 5, 8, 10);
// view
ByteBuffer view = buffer.asReadOnlyBuffer();
assertIndex(view, 2, 5, 8, 10);
}
@Test
public void givenBufferView_whenUsingAsIntBuffer_thenOK() {
// create instance
byte[] bytes = new byte[]{
(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, // CAFEBABE ---> cafebabe
(byte) 0xF0, (byte) 0x07, (byte) 0xBA, (byte) 0x11, // F007BA11 ---> football
(byte) 0x0F, (byte) 0xF1, (byte) 0xCE // 0FF1CE ---> office
};
ByteBuffer buffer = ByteBuffer.wrap(bytes);
assertIndex(buffer, -1, 0, 11, 11);
// view
IntBuffer intBuffer = buffer.asIntBuffer();
int capacity = intBuffer.capacity();
assertEquals(2, capacity);
assertIndex(intBuffer, -1, 0, 2, 2);
}
@Test
public void givenByteOrder_whenUsingBigEndian_thenOK() {
// create instance
byte[] bytes = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
ByteBuffer buffer = ByteBuffer.wrap(bytes);
// change byte order
buffer.order(ByteOrder.BIG_ENDIAN);
int val = buffer.getInt();
// assert
assertEquals(0xCAFEBABE, val);
}
@Test
public void givenByteOrder_whenUsingLittleEndian_thenOK() {
// create instance
byte[] bytes = new byte[]{(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
ByteBuffer buffer = ByteBuffer.wrap(bytes);
// change byte order
buffer.order(ByteOrder.LITTLE_ENDIAN);
int val = buffer.getInt();
// assert
assertEquals(0xBEBAFECA, val);
}
@Test
public void givenComparing_whenUsingEqualsAndCompareTo_thenOK() {
// create instance
byte[] bytes1 = "World".getBytes(StandardCharsets.UTF_8);
byte[] bytes2 = "HelloWorld".getBytes(StandardCharsets.UTF_8);
ByteBuffer buffer1 = ByteBuffer.wrap(bytes1);
ByteBuffer buffer2 = ByteBuffer.wrap(bytes2);
// change index
buffer2.position(5);
// equals and compareTo
boolean equal = buffer1.equals(buffer2);
int result = buffer1.compareTo(buffer2);
// assert
assertTrue(equal);
assertEquals(0, result);
}
private void assertIndex(Buffer buffer, int mark, int position, int limit, int capacity) {
assertEquals(mark, getMark(buffer));
assertEquals(position, buffer.position());
assertEquals(limit, buffer.limit());
assertEquals(capacity, buffer.capacity());
}
private int getMark(Buffer buffer) {
try {
Class<?> clazz = Buffer.class;
Field f = clazz.getDeclaredField("mark");
f.setAccessible(true);
Object result = f.get(buffer);
return (int) result;
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
return -1;
}
}

View File

@ -10,4 +10,5 @@ This module contains articles about core Java Security
- [HMAC in Java](https://www.baeldung.com/java-hmac)
- [Generating a Secure AES Key in Java](https://www.baeldung.com/java-secure-aes-key)
- [Computing an X509 Certificates Thumbprint in Java](https://www.baeldung.com/java-x509-certificate-thumbprint)
- [Error: “trustAnchors parameter must be non-empty”](https://www.baeldung.com/java-trustanchors-parameter-must-be-non-empty)
- More articles: [[<-- prev]](/core-java-modules/core-java-security-2)

View File

@ -38,7 +38,6 @@
<module>core-java-collections-maps</module>
<module>core-java-collections-maps-2</module>
<module>core-java-collections-maps-3</module>
<module>core-java-collections-maps-4</module>
<module>core-java-concurrency-2</module>
<module>core-java-concurrency-advanced</module>
<module>core-java-concurrency-advanced-2</module>

View File

@ -6,3 +6,4 @@
- [How To Configure Java Heap Size Inside a Docker Container](https://www.baeldung.com/ops/docker-jvm-heap-size)
- [Dockerfile Strategies for Git](https://www.baeldung.com/ops/dockerfile-git-strategies)
- [How to Get Docker-Compose to Always Use the Latest Image](https://www.baeldung.com/ops/docker-compose-latest-image)
- [How to Include Files Outside of Dockers Build Context](https://www.baeldung.com/ops/docker-include-files-outside-build-context)

View File

@ -0,0 +1,21 @@
FROM maven:alpine as build
ENV HOME=/usr/app
RUN mkdir -p $HOME
WORKDIR $HOME
ADD pom.xml $HOME
ADD core/pom.xml $HOME/core/pom.xml
ADD runner/pom.xml $HOME/runner/pom.xml
RUN mvn -pl core verify --fail-never
ADD core $HOME/core
RUN mvn -pl core install
RUN mvn -pl runner verify --fail-never
ADD runner $HOME/runner
RUN mvn -pl core,runner package
FROM openjdk:8-jdk-alpine
COPY --from=build /usr/app/runner/target/runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar

View File

@ -0,0 +1,13 @@
FROM maven:alpine as build
ENV HOME=/usr/app
RUN mkdir -p $HOME
WORKDIR $HOME
ADD . $HOME
RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
FROM openjdk:8-jdk-alpine
COPY --from=build /usr/app/runner/target/runner-0.0.1-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core</artifactId>
<parent>
<artifactId>multi-module-caching</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.maven_caching;
import com.google.common.io.Files;
public class CoreClass {
public String method() {
return "Hello from core module!!";
}
public String dependencyMethod() {
return Files.simplifyPath("/home/app/test");
}
}

View File

@ -0,0 +1,29 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>multi-module-caching</artifactId>
<version>0.0.1-SNAPSHOT</version>
<description>Multi-module Maven caching example</description>
<packaging>pom</packaging>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<java.version>1.8</java.version>
</properties>
<modules>
<module>runner</module>
<module>core</module>
</modules>
</project>

View File

@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>runner</artifactId>
<parent>
<artifactId>multi-module-caching</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>core</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.baeldung.maven_caching.MavenCachingApplication</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.maven_caching;
public class MavenCachingApplication {
public static void main(String[] args) {
CoreClass cc = new CoreClass();
System.out.println(cc.method());
System.out.println(cc.dependencyMethod());
}
}

View File

@ -0,0 +1,15 @@
FROM maven:alpine as build
ENV HOME=/usr/app
RUN mkdir -p $HOME
WORKDIR $HOME
ADD pom.xml $HOME
RUN mvn verify --fail-never
ADD . $HOME
RUN mvn package
FROM openjdk:8-jdk-alpine
COPY --from=build /usr/app/target/single-module-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar

View File

@ -0,0 +1,13 @@
FROM maven:alpine as build
ENV HOME=/usr/app
RUN mkdir -p $HOME
WORKDIR $HOME
ADD . $HOME
RUN --mount=type=cache,target=/root/.m2 mvn -f $HOME/pom.xml clean package
FROM openjdk:8-jdk-alpine
COPY --from=build /usr/app/target/single-module-caching-1.0-SNAPSHOT-jar-with-dependencies.jar /app/runner.jar
ENTRYPOINT java -jar /app/runner.jar

View File

@ -0,0 +1,53 @@
<?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>single-module-caching</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.baeldung.maven_caching.MavenCachingMain</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>assemble-all</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.maven_caching;
import com.google.common.io.Files;
public class MavenCachingMain {
public static void main(String[] args) {
System.out.println("Hello from maven_caching app!!!");
System.out.println(Files.simplifyPath("/home/app/test"));
}
}

View File

@ -26,6 +26,8 @@
<module>docker-internal-dto</module>
<module>docker-spring-boot</module>
<module>docker-sample-app</module>
<module>docker-caching/single-module-caching</module>
<module>docker-caching/multi-module-caching</module>
</modules>
</project>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Gradle: sourceCompatiblity vs targetCompatibility](https://www.baeldung.com/gradle-sourcecompatiblity-vs-targetcompatibility)

View File

@ -7,3 +7,4 @@
- [Update the Value Associated With a Key in a HashMap](https://www.baeldung.com/java-hashmap-update-value-by-key)
- [Java Map keySet() vs. entrySet() vs. values() Methods](https://www.baeldung.com/java-map-entries-methods)
- [Java IdentityHashMap Class and Its Use Cases](https://www.baeldung.com/java-identityhashmap)
- [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map)

View File

@ -7,3 +7,4 @@ This module contains articles about the Java Native Interface (JNI).
- [Guide to JNI (Java Native Interface)](https://www.baeldung.com/jni)
- [Using JNA to Access Native Dynamic Libraries](https://www.baeldung.com/java-jna-dynamic-libraries)
- [Check if a Java Program Is Running in 64-Bit or 32-Bit JVM](https://www.baeldung.com/java-detect-jvm-64-or-32-bit)
- [How to use JNIs RegisterNatives() method?](https://www.baeldung.com/jni-registernatives)

View File

@ -15,6 +15,18 @@
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
@ -37,6 +49,7 @@
<properties>
<spring-boot.version>2.4.7</spring-boot.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -0,0 +1,53 @@
<?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">
<parent>
<artifactId>maven-classifier</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-classifier-example-consumer</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>maven-classifier-example-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>maven-classifier-example-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<classifier>arbitrary</classifier>
</dependency>
<!-- For example purpose not building as it requires both JDK 8 and 11 executables on the build machine -->
<!-- <dependency>-->
<!-- <groupId>com.baeldung</groupId>-->
<!-- <artifactId>maven-classifier-example-provider</artifactId>-->
<!-- <version>0.0.1-SNAPSHOT</version>-->
<!-- <classifier>jdk11</classifier>-->
<!-- </dependency>-->
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>maven-classifier-example-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<classifier>sources</classifier>
</dependency>
<dependency>
<groupId>com.baeldung</groupId>
<artifactId>maven-classifier-example-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<classifier>tests</classifier>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.maven.classifier.consumer;
import com.baeldung.maven.dependency.classifier.provider.model.Car;
import com.baeldung.maven.dependency.classifier.provider.model.PowerSource;
public class FuelStation {
public FuelStation.Zone refill(Car car) {
return PowerSource.BATTERY.equals(car.getPowerSource()) ? FuelStation.Zone.BATTERY : FuelStation.Zone.UNKNOWN;
}
public enum Zone {
BATTERY,
UNKNOWN
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.maven.classifier.consumer;
import com.baeldung.maven.classifier.consumer.FuelStation.Zone;
import com.baeldung.maven.dependency.classifier.provider.model.Car;
import com.baeldung.maven.dependency.classifier.provider.stub.CarStub;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class FuelStationUnitTest {
@Test
@DisplayName("Given fuel type battery When request for refill Then Return Battery Zone")
public void givenFuelTypeBattery_whenRequestToRefill_thenReturnBatteryZone() {
FuelStation fuelStation = new FuelStation();
Car electricCar = CarStub.ELECTRIC_CAR;
assertEquals(Zone.BATTERY, fuelStation.refill(electricCar));
}
}

View File

@ -0,0 +1,122 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>maven-classifier</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>maven-classifier-example-provider</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<!-- <jdk.11.executable.path></jdk.11.executable.path>-->
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.0</version>
<executions>
<execution>
<id>JDK 8</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<source>8</source>
<target>8</target>
<fork>true</fork>
</configuration>
</execution>
<!-- For example purpose not building as it requires both JDK 8 and 11 executables on the build machine -->
<!-- <execution>-->
<!-- <id>JDK 11</id>-->
<!-- <phase>compile</phase>-->
<!-- <goals>-->
<!-- <goal>compile</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- <fork>true</fork>-->
<!-- <outputDirectory>${project.build.outputDirectory}_jdk11</outputDirectory>-->
<!-- <executable>${jdk.11.executable.path}</executable>-->
<!-- <source>8</source>-->
<!-- <target>11</target>-->
<!-- </configuration>-->
<!-- </execution>-->
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
<executions>
<execution>
<id>Arbitrary</id>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>arbitrary</classifier>
</configuration>
</execution>
<execution>
<id>Test Jar</id>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
<!-- For example purpose not building as it requires both JDK 8 and 11 executables on the build machine -->
<!-- <execution>-->
<!-- <id>default-package-jdk11</id>-->
<!-- <phase>package</phase>-->
<!-- <goals>-->
<!-- <goal>jar</goal>-->
<!-- </goals>-->
<!-- <configuration>-->
<!-- <classesDirectory>${project.build.outputDirectory}_jdk11</classesDirectory>-->
<!-- <classifier>jdk11</classifier>-->
<!-- </configuration>-->
<!-- </execution>-->
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>verify</phase>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,14 @@
package com.baeldung.maven.dependency.classifier.provider.factory;
import com.baeldung.maven.dependency.classifier.provider.model.Car;
import com.baeldung.maven.dependency.classifier.provider.model.Car.Type;
public class CarFactory {
public static Car manufacture(Type carType) {
Car car = new Car();
car.setType(carType);
return car;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.maven.dependency.classifier.provider.model;
public class Car {
private Type type;
private PowerSource fuelType;
public Type getType() {
return this.type;
}
public void setType(Type carType) {
this.type = carType;
}
public PowerSource getPowerSource() {
return this.fuelType;
}
public void setFuelType(PowerSource fuelType) {
this.fuelType = fuelType;
}
public enum Type {
ELECTRIC
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.maven.dependency.classifier.provider.model;
public enum PowerSource {
BATTERY
}

View File

@ -0,0 +1,32 @@
package com.baeldung.maven.dependency.classifier.provider.factory;
import com.baeldung.maven.dependency.classifier.provider.model.Car;
import com.baeldung.maven.dependency.classifier.provider.model.Car.Type;
import com.baeldung.maven.dependency.classifier.provider.model.PowerSource;
import com.baeldung.maven.dependency.classifier.provider.stub.CarStub;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class CarFactoryUnitTest {
@Test
@DisplayName("Given Car type When CarFactory manufacture is called Then create a Car of the given type")
public void givenCarType_whenCarFactoryManufactureCalled_thenCreateCarOfGivenType() {
Car car = CarFactory.manufacture(Type.ELECTRIC);
assertNotNull(car, "CarFactory didn't manufacture a car. Car is null");
assertEquals(Type.ELECTRIC, car.getType());
}
@Test
@DisplayName("Given an electric car When asked for fuel type Then return Battery")
public void givenElectricCar_whenAskedForFuelType_thenReturnBattery() {
Car car = CarStub.ELECTRIC_CAR;
assertEquals(PowerSource.BATTERY, car.getPowerSource());
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.maven.dependency.classifier.provider.stub;
import com.baeldung.maven.dependency.classifier.provider.model.Car;
import com.baeldung.maven.dependency.classifier.provider.model.PowerSource;
import com.baeldung.maven.dependency.classifier.provider.model.Car.Type;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
public class CarStub {
public static Car ELECTRIC_CAR = Mockito.mock(Car.class);
static {
when(ELECTRIC_CAR.getType()).thenReturn(Type.ELECTRIC);
when(ELECTRIC_CAR.getPowerSource()).thenReturn(PowerSource.BATTERY);
}
}

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-classifier</artifactId>
<packaging>pom</packaging>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>maven-classifier-example-consumer</module>
<module>maven-classifier-example-provider</module>
</modules>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>maven-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>

View File

@ -63,6 +63,7 @@
<properties>
<java.version>11</java.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -36,6 +36,7 @@
<module>maven-surefire-plugin</module>
<module>maven-parent-pom-resolution</module>
<module>maven-simple</module>
<module>maven-classifier</module>
</modules>
<dependencyManagement>

View File

@ -48,6 +48,13 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
@ -63,6 +70,7 @@
<properties>
<camel.version>3.7.4</camel.version>
<spring-boot.version>2.2.2.RELEASE</spring-boot.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,7 @@
## Hibernate Mapping
This module contains articles about Hibernate Mappings.
### Relevant articles
- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many)

View File

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>hibernate-mapping-2y</artifactId>
<version>0.1-SNAPSHOT</version>
<name>hibernate-mapping-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>persistence-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${org.springframework.data.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<!-- validation -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${com.sun.xml.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${javax.xml.bind.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${com.sun.xml.version}</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
<!-- persistence -->
<hibernate.version>5.2.10.Final</hibernate.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<com.sun.xml.version>2.3.0.1</com.sun.xml.version>
<javax.xml.bind.version>2.3.1</javax.xml.bind.version>
</properties>
</project>

View File

@ -1,70 +1,72 @@
package com.baeldung.manytomany.spring;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.hibernate.manytomany" })
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource restDataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "false");
return hibernateProperties;
}
}
package com.baeldung.manytomany;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "com.baeldung.manytomany" })
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.manytomany" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource restDataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "false");
return hibernateProperties;
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.manytomany.dao;
import com.baeldung.manytomany.dao.common.IOperations;
import com.baeldung.manytomany.model.Employee;
public interface IEmployeeDao extends IOperations<Employee>{
}

View File

@ -0,0 +1,8 @@
package com.baeldung.manytomany.dao;
import com.baeldung.manytomany.dao.common.IOperations;
import com.baeldung.manytomany.model.Project;
public interface IProjectDao extends IOperations<Project>{
}

View File

@ -0,0 +1,14 @@
package com.baeldung.manytomany.dao.common;
import java.io.Serializable;
import com.google.common.base.Preconditions;
public abstract class AbstractDao<T extends Serializable> implements IOperations<T> {
protected Class<T> clazz;
protected final void setClazz(final Class<T> clazzToSet) {
clazz = Preconditions.checkNotNull(clazzToSet);
}
}

View File

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

View File

@ -0,0 +1,20 @@
package com.baeldung.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;
public interface IOperations<T extends Serializable> {
T findOne(final long id);
List<T> findAll();
void create(final T entity);
T update(final T entity);
void delete(final T entity);
void deleteById(final long entityId);
}

View File

@ -0,0 +1,17 @@
package com.baeldung.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.manytomany.dao.IEmployeeDao;
import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
import com.baeldung.manytomany.model.Employee;
@Repository
public class EmployeeDao extends AbstractHibernateDao<Employee> implements IEmployeeDao {
public EmployeeDao() {
super();
setClazz(Employee.class);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.manytomany.dao.IProjectDao;
import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
import com.baeldung.manytomany.model.Project;
@Repository
public class ProjectDao extends AbstractHibernateDao<Project> implements IProjectDao {
public ProjectDao() {
super();
setClazz(Project.class);
}
}

View File

@ -1,88 +1,88 @@
package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Employee")
public class Employee implements Serializable {
@Id
@Column(name = "employee_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Employee_Project",
joinColumns = { @JoinColumn(name = "employee_id") },
inverseJoinColumns = { @JoinColumn(name = "project_id") }
)
Set<Project> projects = new HashSet<Project>();
public Employee() {
super();
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(String firstName, String lastName, Set<Project> projects) {
this.firstName = firstName;
this.lastName = lastName;
this.projects = projects;
}
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
}
package com.baeldung.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Employee")
public class Employee implements Serializable {
@Id
@Column(name = "employee_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long employeeId;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Employee_Project",
joinColumns = { @JoinColumn(name = "employee_id") },
inverseJoinColumns = { @JoinColumn(name = "project_id") }
)
Set<Project> projects = new HashSet<Project>();
public Employee() {
super();
}
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Employee(String firstName, String lastName, Set<Project> projects) {
this.firstName = firstName;
this.lastName = lastName;
this.projects = projects;
}
public Long getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Long employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
}

View File

@ -1,61 +1,62 @@
package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Project")
public class Project implements Serializable {
@Id
@Column(name = "project_id")
@GeneratedValue
private Long projectId;
@Column(name = "title")
private String title;
@ManyToMany(mappedBy = "projects")
private Set<Employee> employees = new HashSet<Employee>();
public Project() {
super();
}
public Project(String title) {
this.title = title;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
package com.baeldung.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Project")
public class Project implements Serializable {
@Id
@Column(name = "project_id")
@GeneratedValue
private Long projectId;
@Column(name = "title")
private String title;
@ManyToMany(mappedBy = "projects")
private Set<Employee> employees = new HashSet<Employee>();
public Project() {
super();
}
public Project(String title) {
this.title = title;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}

View File

@ -1,45 +1,46 @@
package com.baeldung.hibernate.manytomany.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Project.class);
configuration.configure("manytomany.cfg.xml");
LOGGER.debug("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
LOGGER.debug("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}
package com.baeldung.manytomany.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
public class HibernateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Project.class);
configuration.configure("manytomany.cfg.xml");
LOGGER.debug("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
LOGGER.debug("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable ex) {
LOGGER.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,11 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.eventGeneratedId=sa
jdbc.user=sa
jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

View File

@ -0,0 +1,18 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.manytomany.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,49 +1,50 @@
package com.baeldung.hibernate.manytomany;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
import com.baeldung.manytomany.spring.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
private Session session;
@Before
public final void before() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@After
public final void after() {
session.getTransaction().commit();
session.close();
}
@Test
public final void whenEntitiesAreCreated_thenNoExceptions() {
Set<Project> projects = new HashSet<Project>();
projects.add(new Project("IT Project"));
projects.add(new Project("Networking Project"));
session.persist(new Employee("Peter", "Oven", projects));
session.persist(new Employee("Allan", "Norman", projects));
}
}
package com.baeldung.hibernate.manytomany;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.manytomany.PersistenceConfig;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class HibernateManyToManyAnnotationJavaConfigMainIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
private Session session;
@Before
public final void before() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@After
public final void after() {
session.getTransaction().commit();
session.close();
}
@Test
public final void whenEntitiesAreCreated_thenNoExceptions() {
Set<Project> projects = new HashSet<Project>();
projects.add(new Project("IT Project"));
projects.add(new Project("Networking Project"));
session.persist(new Employee("Peter", "Oven", projects));
session.persist(new Employee("Allan", "Norman", projects));
}
}

View File

@ -1,80 +1,82 @@
package com.baeldung.hibernate.manytomany;
import static org.junit.Assert.assertNotNull;
import static junit.framework.TestCase.assertEquals;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.hibernate.manytomany.util.HibernateUtil;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
/**
* Configured in: manytomany.cfg.xml
*/
public class HibernateManyToManyAnnotationMainIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsert_thenCreatesMtoMrelationship() {
String[] employeeData = { "Peter Oven", "Allan Norman" };
String[] projectData = { "IT Project", "Networking Project" };
Set<Project> projects = new HashSet<Project>();
for (String proj : projectData) {
projects.add(new Project(proj));
}
for (String emp : employeeData) {
Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
assertEquals(0, employee.getProjects().size());
employee.setProjects(projects);
session.persist(employee);
assertNotNull(employee);
}
}
@Test
public void givenSession_whenRead_thenReturnsMtoMdata() {
@SuppressWarnings("unchecked")
List<Employee> employeeList = session.createQuery("FROM Employee").list();
assertNotNull(employeeList);
for(Employee employee : employeeList) {
assertNotNull(employee.getProjects());
}
}
@After
public void tearDown() {
session.getTransaction()
.commit();
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}
package com.baeldung.hibernate.manytomany;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.manytomany.model.Employee;
import com.baeldung.manytomany.model.Project;
import com.baeldung.manytomany.util.HibernateUtil;
/**
* Configured in: manytomany.cfg.xml
*/
public class HibernateManyToManyAnnotationMainIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory();
}
@Before
public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
}
@Test
public void givenData_whenInsert_thenCreatesMtoMrelationship() {
String[] employeeData = { "Peter Oven", "Allan Norman" };
String[] projectData = { "IT Project", "Networking Project" };
Set<Project> projects = new HashSet<Project>();
for (String proj : projectData) {
projects.add(new Project(proj));
}
for (String emp : employeeData) {
Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
assertEquals(0, employee.getProjects().size());
employee.setProjects(projects);
session.persist(employee);
assertNotNull(employee);
}
}
@Test
public void givenSession_whenRead_thenReturnsMtoMdata() {
@SuppressWarnings("unchecked")
List<Employee> employeeList = session.createQuery("FROM Employee").list();
assertNotNull(employeeList);
for(Employee employee : employeeList) {
assertNotNull(employee.getProjects());
}
}
@After
public void tearDown() {
session.getTransaction()
.commit();
session.close();
}
@AfterClass
public static void afterTests() {
sessionFactory.close();
}
}

View File

@ -13,4 +13,4 @@
<property name="hibernate.show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
</session-factory>
</hibernate-configuration>
</hibernate-configuration>

View File

@ -7,4 +7,5 @@ This module contains articles about use of Queries in Hibernate.
- [Criteria Queries Using JPA Metamodel](https://www.baeldung.com/hibernate-criteria-queries-metamodel)
- [Get All Data from a Table with Hibernate](https://www.baeldung.com/hibernate-select-all)
- [Hibernate Named Query](https://www.baeldung.com/hibernate-named-query)
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
- [Hibernate Query Plan Cache](https://www.baeldung.com/hibernate-query-plan-cache)
- [Hibernates addScalar() Method](https://www.baeldung.com/hibernate-addscalar)

View File

@ -0,0 +1,44 @@
package com.baeldung.mongo.update;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
public class MultipleFieldsExample {
public static void main(String[] args) {
//
// Connect to cluster (default is localhost:27017)
//
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("employee");
//
// Filter on the basis of employee_id
//
BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
//
// Update the fields in Document
//
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("department_id", 3);
updateFields.append("job", "Sales Manager");
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);
System.out.println("updateResult:- " + updateResult);
System.out.println("updateResult:- " + updateResult.getModifiedCount());
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.mongo.update;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
public class UpdateMultipleFields {
public static void main(String[] args) {
//
// Connect to cluster
//
MongoClient mongoClient = new MongoClient("localhost", 27007);
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("employee");
//
// Update query
//
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875),
Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
System.out.println("updateResult:- " + updateResult);
System.out.println("updateResult:- " + updateResult.getModifiedCount());
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.update;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
public class UpdateMultipleFieldsLiveTest {
private MongoClient mongoClient;
private MongoDatabase db;
private MongoCollection<Document> collection;
@Before
public void setup() {
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDatabase("baeldung");
collection = db.getCollection("employee");
collection.insertOne(Document.parse(
"{'employee_id':794875,'employee_name': 'David smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
}
}
@Test
public void updateMultipleFieldsUsingDBObject() {
BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("department_id", 4);
updateFields.append("job", "Sales Manager");
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
collection.updateMany(searchQuery, setQuery);
Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
assertNotNull(nameDoc);
assertFalse(nameDoc.isEmpty());
String job = nameDoc.get("job", String.class);
assertNotNull(job);
Integer department_id = nameDoc.get("department_id", Integer.class);
assertNotNull(department_id);
}
@Test
public void updateMultipleFieldsUsingDocument() {
collection.updateMany(Filters.eq("employee_id", 794875),
Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
assertNotNull(nameDoc);
assertFalse(nameDoc.isEmpty());
String job = nameDoc.get("job", String.class);
assertNotNull(job);
Integer department_id = nameDoc.get("department_id", Integer.class);
assertNotNull(department_id);
}
}

View File

@ -24,6 +24,13 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
@ -184,6 +191,7 @@
<dynamodblocal.repository.url>https://s3-us-west-2.amazonaws.com/dynamodb-local/release</dynamodblocal.repository.url>
<maven-dependency-plugin.version>3.1.1</maven-dependency-plugin.version>
<spring-boot.version>2.4.7</spring-boot.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -4,7 +4,6 @@ This module contains articles about Hibernate 5 with Spring.
### Relevant articles
- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many)
- [Programmatic Transactions in the Spring TestContext Framework](https://www.baeldung.com/spring-test-programmatic-transactions)
- [JPA Criteria Queries](https://www.baeldung.com/hibernate-criteria-queries)
- [Introduction to Hibernate Search](https://www.baeldung.com/hibernate-search)

View File

@ -107,7 +107,22 @@
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${com.sun.xml.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${javax.xml.bind.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${com.sun.xml.version}</version>
</dependency>
</dependencies>
<properties>
@ -122,6 +137,8 @@
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<hsqldb.version>2.3.4</hsqldb.version>
<com.sun.xml.version>2.3.0.1</com.sun.xml.version>
<javax.xml.bind.version>2.3.1</javax.xml.bind.version>
</properties>
</project>

View File

@ -1,8 +0,0 @@
package com.baeldung.persistence.manytomany.dao;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.persistence.dao.common.IOperations;
public interface IEmployeeDao extends IOperations<Employee>{
}

View File

@ -1,8 +0,0 @@
package com.baeldung.persistence.manytomany.dao;
import com.baeldung.hibernate.manytomany.model.Project;
import com.baeldung.persistence.dao.common.IOperations;
public interface IProjectDao extends IOperations<Project>{
}

View File

@ -1,16 +0,0 @@
package com.baeldung.persistence.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.manytomany.dao.IEmployeeDao;
@Repository
public class EmployeeDao extends AbstractHibernateDao<Employee> implements IEmployeeDao {
public EmployeeDao() {
super();
setClazz(Employee.class);
}
}

View File

@ -1,17 +0,0 @@
package com.baeldung.persistence.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
import com.baeldung.hibernate.manytomany.model.Project;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
import com.baeldung.persistence.manytomany.dao.IProjectDao;
@Repository
public class ProjectDao extends AbstractHibernateDao<Project> implements IProjectDao {
public ProjectDao() {
super();
setClazz(Project.class);
}
}

View File

@ -1,15 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">tutorialmy5ql</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_hibernate_many_to_many</property>
<property name="hibernate.connection.username">tutorialuser</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
</session-factory>
</hibernate-configuration>

View File

@ -11,6 +11,7 @@
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="hibernate.hbm2ddl.import_files">import-db.sql</property>
<property name="show_sql">false</property>
<mapping resource="com/baeldung/hibernate/criteria/model/Item.hbm.xml" />
</session-factory>

View File

@ -1,3 +1,4 @@
insert into item (item_id, item_name, item_desc, item_price) values(1,'item One', 'test 1', 35.12);
insert into item (item_id, item_name, item_desc, item_price) values(2,'Pogo stick', 'Pogo stick', 466.12);

28
pom.xml
View File

@ -400,7 +400,6 @@
<module>dagger</module>
<module>data-structures</module>
<module>ddd</module>
<!-- <module>ddd-modules</module>--> <!-- we haven't upgraded to Java 9 -->
<module>deeplearning4j</module>
<module>discord4j</module>
<module>disruptor</module>
@ -432,7 +431,6 @@
<module>hazelcast</module>
<module>helidon</module>
<module>httpclient</module>
<!--<module>httpclient-2</module>--><!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>httpclient-simple</module>
<module>hystrix</module>
@ -483,8 +481,8 @@
<module>kubernetes</module>
<module>ksqldb</module>
<!-- <module>lagom</module> --> <!-- Not a maven project -->
<module>language-interop</module>
<module>libraries-2</module>
<module>language-interop</module>
<module>libraries-2</module>
<module>libraries-3</module>
<module>libraries-apache-commons</module>
<module>libraries-apache-commons-collections</module>
@ -520,12 +518,12 @@
<module>micronaut</module>
<module>microprofile</module>
<module>msf4j</module>
<!-- <module>muleesb</module> --> <!-- Module broken, fixing in http://team.baeldung.com/browse/BAEL-20604 -->
<!-- <module>muleesb</module> --> <!-- Module broken, fixing in https://team.baeldung.com/browse/JAVA-10335 -->
<module>mustache</module>
<module>mybatis</module>
<module>netflix-modules</module>
<!-- <module>netty</module> --> <!-- we haven't upgraded to Java 13 -->
<module>netty</module>
<module>ninja</module>
<module>open-liberty</module>
@ -886,7 +884,6 @@
<module>dagger</module>
<module>data-structures</module>
<module>ddd</module>
<!-- <module>ddd-modules</module>--> <!-- we haven't upgraded to Java 9 -->
<module>deeplearning4j</module>
<module>discord4j</module>
<module>disruptor</module>
@ -917,7 +914,6 @@
<module>hazelcast</module>
<module>helidon</module>
<module>httpclient</module>
<!--<module>httpclient-2</module>--><!-- to be fixed in http://team.baeldung.com/browse/JAVA-2824 -->
<module>httpclient-simple</module>
<module>hystrix</module>
@ -1005,12 +1001,12 @@
<module>micronaut</module>
<module>microprofile</module>
<module>msf4j</module>
<!-- <module>muleesb</module> --> <!-- Module broken, fixing in http://team.baeldung.com/browse/BAEL-20604 -->
<!-- <module>muleesb</module> --> <!-- Module broken, fixing in https://team.baeldung.com/browse/JAVA-10335 -->
<module>mustache</module>
<module>mybatis</module>
<module>netflix-modules</module>
<!-- <module>netty</module> --> <!-- we haven't upgraded to Java 13 -->
<module>netty</module>
<module>ninja</module>
<module>open-liberty</module>
@ -1200,7 +1196,6 @@
<module>wildfly</module>
<module>xml</module>
<module>xstream</module>
<!-- <module>libraries-concurrency</module>--> <!-- we haven't upgraded to Java 11 -->
</modules>
</profile>
@ -1329,6 +1324,7 @@
<!-- <module>core-java-modules/core-java-14</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-15</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-collections-set</module>
<module>core-java-modules/core-java-collections-maps-4</module>
<module>core-java-modules/core-java-date-operations-1</module>
<module>core-java-modules/core-java-datetime-conversion</module>
<module>core-java-modules/core-java-datetime-string</module>
@ -1341,11 +1337,15 @@
<module>core-java-modules/core-java-time-measurements</module>
<module>core-java-modules/core-java-networking-3</module>
<module>core-java-modules/multimodulemavenproject</module>
<module>ddd-modules</module>
<module>httpclient-2</module>
<module>libraries-concurrency</module>
<module>persistence-modules/sirix</module>
<module>persistence-modules/spring-data-cassandra-2</module>
<module>quarkus-vs-springboot</module>
<module>quarkus-jandex</module>
<module>spring-boot-modules/spring-boot-cassandre</module>
<module>spring-boot-modules/spring-boot-camel</module>
<module>testing-modules/testing-assertions</module>
</modules>
</profile>
@ -1386,6 +1386,7 @@
<!-- <module>core-java-modules/core-java-14</module> --> <!-- uses preview features, to be decided how to handle -->
<!-- <module>core-java-modules/core-java-15</module> --> <!-- uses preview features, to be decided how to handle -->
<module>core-java-modules/core-java-collections-set</module>
<module>core-java-modules/core-java-collections-maps-4</module>
<module>core-java-modules/core-java-date-operations-1</module>
<module>core-java-modules/core-java-datetime-conversion</module>
<module>core-java-modules/core-java-datetime-string</module>
@ -1398,11 +1399,15 @@
<module>core-java-modules/core-java-networking-3</module>
<module>core-java-modules/multimodulemavenproject</module>
<module>core-java-modules/core-java-strings</module>
<module>ddd-modules</module>
<module>httpclient-2</module>
<module>libraries-concurrency</module>
<module>persistence-modules/sirix</module>
<module>persistence-modules/spring-data-cassandra-2</module>
<module>quarkus-vs-springboot</module>
<module>quarkus-jandex</module>
<module>spring-boot-modules/spring-boot-cassandre</module>
<module>spring-boot-modules/spring-boot-camel</module>
<module>testing-modules/testing-assertions</module>
</modules>
</profile>
@ -1470,7 +1475,6 @@
<custom-pmd.version>0.0.1</custom-pmd.version>
<gitflow-incremental-builder.version>3.12.2</gitflow-incremental-builder.version>
<maven-jxr-plugin.version>3.0.0</maven-jxr-plugin.version>
<!-- <maven-pmd-plugin.version>3.9.0</maven-pmd-plugin.version> -->
<maven-pmd-plugin.version>3.13.0</maven-pmd-plugin.version>
<lombok.version>1.18.20</lombok.version>
<h2.version>1.4.200</h2.version>

View File

@ -187,6 +187,7 @@
<java.version>11</java.version>
<repackage.classifier />
<spring-native.version>0.11.0-RC1</spring-native.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -0,0 +1,3 @@
### Relevant Articles:
- [Spring @Autowired Field Null Common Causes and Solutions](https://www.baeldung.com/spring-autowired-field-null)

View File

@ -13,6 +13,18 @@
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
@ -138,6 +150,7 @@
<reactor-core.version>3.3.1.RELEASE</reactor-core.version>
<!-- This spring-boot.version is set manually, For upgrading this please refer http://team.baeldung.com/browse/JAVA-2802 -->
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -16,6 +16,18 @@
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-1</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
@ -59,6 +71,7 @@
<properties>
<activiti.version>6.0.0</activiti.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -36,7 +36,6 @@
<module>spring-boot-deployment</module>
<module>spring-boot-di</module>
<module>spring-boot-disable-logging</module>
<module>spring-boot-camel</module>
<module>spring-boot-ci-cd</module>
<!-- <module>spring-boot-cli</module> --> <!-- Not a maven project -->
<module>spring-boot-custom-starter</module>

View File

@ -62,7 +62,7 @@
</build>
<properties>
<log4j2.version>2.14.1</log4j2.version>
<log4j2.version>2.17.1</log4j2.version>
<spring-core.version>5.3.15</spring-core.version>
<maven.compiler.target>11</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>

View File

@ -16,22 +16,22 @@
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-servlet-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jackson-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-swagger-java-starter</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>${camel.version}</version>
</dependency>
@ -64,7 +64,8 @@
</build>
<properties>
<camel.version>3.0.0-M4</camel.version>
<java.version>11</java.version>
<camel.version>3.15.0</camel.version>
</properties>
</project>

View File

@ -4,4 +4,4 @@ This module contains articles about various Spring Boot libraries Comparison
### Relevant Articles:
- [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest/)
- [GraphQL vs REST](https://www.baeldung.com/graphql-vs-rest)

View File

@ -102,6 +102,7 @@
<!-- used only in dependency management to force this version, not included as a direct dependency -->
<junit.version>4.13.2</junit.version>
<junit-jupiter.version>5.8.1</junit-jupiter.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -70,6 +70,7 @@
<maven.compiler.target>1.8</maven.compiler.target>
<eclipse.birt.runtime.version>4.8.0</eclipse.birt.runtime.version>
<log4j.version>1.2.17</log4j.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -11,6 +11,18 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -128,6 +140,7 @@
<yarn.version>v1.12.1</yarn.version>
<spring-boot.version>2.4.4</spring-boot.version>
<javafaker.version>1.0.2</javafaker.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -10,6 +10,7 @@ This module contains articles about Spring Boot Security
- [Guide to @CurrentSecurityContext in Spring Security](https://www.baeldung.com/spring-currentsecuritycontext)
- [Disable Security for a Profile in Spring Boot](https://www.baeldung.com/spring-security-disable-profile)
- [Spring @EnableWebSecurity vs. @EnableGlobalMethodSecurity](https://www.baeldung.com/spring-enablewebsecurity-vs-enableglobalmethodsecurity)
- [Spring Security Configuring Different URLs](https://www.baeldung.com/spring-security-configuring-urls)
### Spring Boot Security Auto-Configuration

View File

@ -24,6 +24,13 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
@ -62,6 +69,7 @@
<spring-boot.version>2.4.5</spring-boot.version>
<springfox.version>3.0.0</springfox.version>
<keycloak.version>15.0.2</keycloak.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -5,3 +5,4 @@
- [Generate PDF from Swagger API Documentation](https://www.baeldung.com/swagger-generate-pdf)
- [Remove Basic Error Controller In SpringFox Swagger-UI](https://www.baeldung.com/spring-swagger-remove-error-controller)
- [Setting Example and Description with Swagger](https://www.baeldung.com/swagger-set-example-description)
- [Document Enum in Swagger](https://www.baeldung.com/swagger-enum)

View File

@ -14,6 +14,18 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -131,6 +143,7 @@
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
<redis.version>0.7.2</redis.version>
<spring-boot.version>2.5.0</spring-boot.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -21,6 +21,13 @@
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
@ -55,6 +62,7 @@
<properties>
<spring-cloud.version>2.1.1.RELEASE</spring-cloud.version>
<spring-boot.version>2.1.4.RELEASE</spring-boot.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -14,6 +14,18 @@
<artifactId>spring-cloud</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>spring-cloud-eureka-server</module>
@ -32,6 +44,7 @@
<properties>
<spring-boot.version>2.1.3.RELEASE</spring-boot.version>
<spring-cloud-dependencies.version>Greenwich.SR3</spring-cloud-dependencies.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -14,6 +14,18 @@
<artifactId>spring-cloud</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>spring-cloud-eureka-server</module>
@ -34,6 +46,7 @@
<properties>
<spring-boot.version>2.1.2.RELEASE</spring-boot.version>
<spring-cloud-dependencies.version>Greenwich.RELEASE</spring-cloud-dependencies.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -19,6 +19,18 @@
<module>spring-cloud-loadbalancer-server</module>
<module>spring-cloud-loadbalancer-client</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
@ -32,6 +44,7 @@
<properties>
<spring-boot.version>2.6.1</spring-boot.version>
<spring-cloud.version>2021.0.0</spring-cloud.version>
<log4j2.version>2.17.1</log4j2.version>
</properties>
</project>

View File

@ -4,3 +4,4 @@
- [Differences Between Netflix Feign and OpenFeign](https://www.baeldung.com/netflix-feign-vs-openfeign)
- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload)
- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging)
- [Provide an OAuth2 Token to a Feign Client](https://www.baeldung.com/spring-cloud-feign-oauth-token)

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