This commit is contained in:
Alessio Stalla 2019-05-14 22:41:05 +02:00
commit 9a7b968d02
205 changed files with 5582 additions and 711 deletions

View File

@ -15,3 +15,5 @@
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)

View File

@ -4,4 +4,3 @@
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)

View File

@ -3,5 +3,5 @@
## Relevant articles:
- [String Matching in Groovy](http://www.baeldung.com/)
- [Groovy def Keyword]
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)

View File

@ -0,0 +1,5 @@
Dear <% out << (user) %>,
Please read the requested article below.
<% out << (articleText) %>
From,
<% out << (signature) %>

View File

@ -0,0 +1,3 @@
Dear $user,
Thanks for subscribing our services.
${signature}

View File

@ -0,0 +1,96 @@
package com.baeldung.templateengine
import groovy.text.SimpleTemplateEngine
import groovy.text.StreamingTemplateEngine
import groovy.text.GStringTemplateEngine
import groovy.text.XmlTemplateEngine
import groovy.text.XmlTemplateEngine
import groovy.text.markup.MarkupTemplateEngine
import groovy.text.markup.TemplateConfiguration
class TemplateEnginesUnitTest extends GroovyTestCase {
def bindMap = [user: "Norman", signature: "Baeldung"]
void testSimpleTemplateEngine() {
def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}'
def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap)
assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"
}
void testStreamingTemplateEngine() {
def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
bindMap.articleText = """1. Overview
This is a tutorial article on Template Engines""" //can be a string larger than 64k
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap)
assert articleEmailText.toString() == """Dear Norman,
Please read the requested article below.
1. Overview
This is a tutorial article on Template Engines
From,
Baeldung"""
}
void testGStringTemplateEngine() {
def emailTemplate = new File('src/main/resources/email.template')
def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap)
assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung"
}
void testXmlTemplateEngine() {
def emailXmlTemplate = '''<xs xmlns:gsp='groovy-server-pages'>
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
<email>
<greet>Dear ${user}</greet>
<content><gsp:expression>emailContent</gsp:expression></content>
<signature>${signature}</signature>
</email>
</xs>'''
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
println emailXml.toString()
}
void testMarkupTemplateEngineHtml() {
def emailHtmlTemplate = """html {
head {
title('Service Subscription Email')
}
body {
p('Dear Norman')
p('Thanks for subscribing our services.')
p('Baeldung')
}
}"""
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
println emailHtml.toString()
}
void testMarkupTemplateEngineXml() {
def emailXmlTemplate = """xmlDeclaration()
xs{
email {
greet('Dear Norman')
content('Thanks for subscribing our services.')
signature('Baeldung')
}
}
"""
TemplateConfiguration config = new TemplateConfiguration()
config.autoIndent = true
config.autoEscape = true
config.autoNewLine = true
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
println emailXml.toString()
}
}

View File

@ -2,5 +2,5 @@
## Relevant articles:
- [Maps in Groovy](http://www.baeldung.com/)
- [Maps in Groovy](https://www.baeldung.com/groovy-maps)

View File

@ -0,0 +1,3 @@
## Relevant Articles
- [Extending an Arrays Length](https://www.baeldung.com/java-array-add-element-at-the-end)

View File

@ -0,0 +1,52 @@
package com.baeldung.array.conversions;
import java.util.Arrays;
import java.util.function.IntFunction;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamArrayConversion {
public static String[] stringStreamToStringArrayUsingFunctionalInterface(Stream<String> stringStream) {
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
@Override
public String[] apply(int value) {
return new String[value];
}
};
return stringStream.toArray(intFunction);
}
public static String[] stringStreamToStringArrayUsingMethodReference(Stream<String> stringStream) {
return stringStream.toArray(String[]::new);
}
public static String[] stringStreamToStringArrayUsingLambda(Stream<String> stringStream) {
return stringStream.toArray(value -> new String[value]);
}
public static Integer[] integerStreamToIntegerArray(Stream<Integer> integerStream) {
return integerStream.toArray(Integer[]::new);
}
public static int[] intStreamToPrimitiveIntArray(Stream<Integer> integerStream) {
return integerStream.mapToInt(i -> i).toArray();
}
public static Stream<String> stringArrayToStreamUsingArraysStream(String[] stringArray) {
return Arrays.stream(stringArray);
}
public static Stream<String> stringArrayToStreamUsingStreamOf(String[] stringArray) {
return Stream.of(stringArray);
}
public static IntStream primitiveIntArrayToStreamUsingArraysStream(int[] intArray) {
return Arrays.stream(intArray);
}
public static Stream<int[]> primitiveIntArrayToStreamUsingStreamOf(int[] intArray) {
return Stream.of(intArray);
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.array.conversions;
import static com.baeldung.array.conversions.StreamArrayConversion.intStreamToPrimitiveIntArray;
import static com.baeldung.array.conversions.StreamArrayConversion.integerStreamToIntegerArray;
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingFunctionalInterface;
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingLambda;
import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingMethodReference;
import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingArraysStream;
import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingStreamOf;
import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingArraysStream;
import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingStreamOf;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.Iterators;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
public class StreamArrayConversionUnitTest {
private String[] stringArray = new String[]{"baeldung", "convert", "to", "string", "array"};
private Integer[] integerArray = new Integer[]{1, 2, 3, 4, 5, 6, 7};
private int[] intPrimitiveArray = new int[]{1, 2, 3, 4, 5, 6, 7};
@Test
public void givenStringStream_thenConvertToStringArrayUsingFunctionalInterface() {
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
assertArrayEquals(stringArray, stringStreamToStringArrayUsingFunctionalInterface(stringStream));
}
@Test
public void givenStringStream_thenConvertToStringArrayUsingMethodReference() {
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
assertArrayEquals(stringArray, stringStreamToStringArrayUsingMethodReference(stringStream));
}
@Test
public void givenStringStream_thenConvertToStringArrayUsingLambda() {
Stream<String> stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
assertArrayEquals(stringArray, stringStreamToStringArrayUsingLambda(stringStream));
}
@Test
public void givenIntegerStream_thenConvertToIntegerArray() {
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
assertArrayEquals(integerArray, integerStreamToIntegerArray(integerStream));
}
@Test
public void givenIntStream_thenConvertToIntegerArray() {
Stream<Integer> integerStream = IntStream.rangeClosed(1, 7).boxed();
assertArrayEquals(intPrimitiveArray, intStreamToPrimitiveIntArray(integerStream));
}
@Test
public void givenStringArray_whenConvertedTwoWays_thenConvertedStreamsAreEqual() {
assertTrue(Iterators
.elementsEqual(stringArrayToStreamUsingArraysStream(stringArray).iterator(),
stringArrayToStreamUsingStreamOf(stringArray).iterator()));
}
@Test
public void givenPrimitiveArray_whenConvertedTwoWays_thenConvertedStreamsAreNotEqual() {
assertFalse(Iterators.elementsEqual(
primitiveIntArrayToStreamUsingArraysStream(intPrimitiveArray).iterator(),
primitiveIntArrayToStreamUsingStreamOf(intPrimitiveArray).iterator()));
}
}

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-lambda-effectively-final-local-variables)

View File

@ -7,3 +7,4 @@
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
- [Guide to jlink](https://www.baeldung.com/jlink)
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)

View File

@ -3,4 +3,5 @@
## Core Java 8 Cookbooks and Examples (part 2)
### Relevant Articles:
- [Anonymous Classes in Java](http://www.baeldung.com/)
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)

View File

@ -101,7 +101,7 @@ public class OptionalChainingUnitTest {
}
private Optional<String> createOptional(String input) {
if (input == null || input == "" || input == "empty") {
if (input == null || "".equals(input) || "empty".equals(input)) {
return Optional.empty();
}

View File

@ -20,6 +20,14 @@
- [Multi-Release Jar Files](https://www.baeldung.com/java-multi-release-jar)
- [Ahead of Time Compilation (AoT)](https://www.baeldung.com/ahead-of-time-compilation)
- [Java 9 Process API Improvements](https://www.baeldung.com/java-9-process-api)
- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
- [Java 9 java.util.Objects Additions](https://www.baeldung.com/java-9-objects-new)
- [Java 9 Reactive Streams](https://www.baeldung.com/java-9-reactive-streams)
- [Java 9 Optional API Additions](https://www.baeldung.com/java-9-optional)
- [Java 9 CompletableFuture API Improvements](https://www.baeldung.com/java-9-completablefuture)
- [Introduction to Java 9 StackWalking API](https://www.baeldung.com/java-9-stackwalking-api)
- [Java 9 Convenience Factory Methods for Collections](https://www.baeldung.com/java-9-collections-factory-methods)
- [Java 9 Stream API Improvements](https://www.baeldung.com/java-9-stream-api)
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 Platform Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
- [Filtering a Stream of Optionals in Java](https://www.baeldung.com/java-filter-stream-of-optional)

View File

@ -8,4 +8,5 @@
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
- [Set Operations in Java](https://www.baeldung.com/java-set-operations)

View File

@ -0,0 +1,26 @@
<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.exception.numberformat</groupId>
<artifactId>core-java-exceptions</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>core-java-exceptions</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,154 @@
package com.baeldung.exception.numberformat;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.logging.Logger;
import org.junit.Test;
/**
* A set of examples tested to show cases where NumberFormatException is thrown and not thrown.
*/
public class NumberFormatExceptionUnitTest {
Logger LOG = Logger.getLogger(NumberFormatExceptionUnitTest.class.getName());
/* ---INTEGER FAIL CASES--- */
@Test(expected = NumberFormatException.class)
public void givenByteConstructor_whenAlphabetAsInput_thenFail() {
Byte byteInt = new Byte("one");
}
@Test(expected = NumberFormatException.class)
public void givenShortConstructor_whenSpaceInInput_thenFail() {
Short shortInt = new Short("2 ");
}
@Test(expected = NumberFormatException.class)
public void givenParseIntMethod_whenSpaceInInput_thenFail() {
Integer aIntPrim = Integer.parseInt("6000 ");
}
@Test(expected = NumberFormatException.class)
public void givenParseIntMethod_whenUnderscoreInInput_thenFail() {
int bIntPrim = Integer.parseInt("6_000");
}
@Test(expected = NumberFormatException.class)
public void givenIntegerValueOfMethod_whenCommaInInput_thenFail() {
Integer cIntPrim = Integer.valueOf("6,000");
}
@Test(expected = NumberFormatException.class)
public void givenBigIntegerConstructor_whenDecimalInInput_thenFail() {
BigInteger bigInteger = new BigInteger("4.0");
}
@Test(expected = NumberFormatException.class)
public void givenDecodeMethod_whenAlphabetInInput_thenFail() {
Long decodeInteger = Long.decode("64403L");
}
/* ---INTEGER PASS CASES--- */
@Test
public void givenInvalidNumberInputs_whenOptimized_thenPass() {
Byte byteInt = new Byte("1");
assertEquals(1, byteInt.intValue());
Short shortInt = new Short("2 ".trim());
assertEquals(2, shortInt.intValue());
Integer aIntObj = Integer.valueOf("6");
assertEquals(6, aIntObj.intValue());
BigInteger bigInteger = new BigInteger("4");
assertEquals(4, bigInteger.intValue());
int aIntPrim = Integer.parseInt("6000 ".trim());
assertEquals(6000, aIntPrim);
int bIntPrim = Integer.parseInt("6_000".replaceAll("_", ""));
assertEquals(6000, bIntPrim);
int cIntPrim = Integer.parseInt("-6000");
assertEquals(-6000, cIntPrim);
Long decodeInteger = Long.decode("644032334");
assertEquals(644032334L, decodeInteger.longValue());
}
/* ---DOUBLE FAIL CASES--- */
@Test(expected = NumberFormatException.class)
public void givenFloatConstructor_whenAlphabetInInput_thenFail() {
Float floatDecimalObj = new Float("one.1");
}
@Test(expected = NumberFormatException.class)
public void givenDoubleConstructor_whenAlphabetInInput_thenFail() {
Double doubleDecimalObj = new Double("two.2");
}
@Test(expected = NumberFormatException.class)
public void givenBigDecimalConstructor_whenSpecialCharsInInput_thenFail() {
BigDecimal bigDecimalObj = new BigDecimal("3_0.3");
}
@Test(expected = NumberFormatException.class)
public void givenParseDoubleMethod_whenCommaInInput_thenFail() {
double aDoublePrim = Double.parseDouble("4000,1");
}
/* ---DOUBLE PASS CASES--- */
@Test
public void givenDoubleConstructor_whenDecimalInInput_thenPass() {
Double doubleDecimalObj = new Double("2.2");
assertEquals(2.2, doubleDecimalObj.doubleValue(), 0);
}
@Test
public void givenDoubleValueOfMethod_whenMinusInInput_thenPass() {
Double aDoubleObj = Double.valueOf("-6000");
assertEquals(-6000, aDoubleObj.doubleValue(), 0);
}
@Test
public void givenUsDecimalNumber_whenParsedWithNumberFormat_thenPass() throws ParseException {
Number parsedNumber = parseNumberWithLocale("4000.1", Locale.US);
assertEquals(4000.1, parsedNumber);
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
assertEquals(4000, parsedNumber.intValue());
}
/**
* In most European countries (for example, France), comma is used as decimal in place of period.
* @throws ParseException if the input string contains special characters other than comma or decimal.
* In this test case, anything after decimal (period) is dropped when a European locale is set.
*/
@Test
public void givenEuDecimalNumberHasComma_whenParsedWithNumberFormat_thenPass() throws ParseException {
Number parsedNumber = parseNumberWithLocale("4000,1", Locale.FRANCE);
LOG.info("Number parsed is: " + parsedNumber);
assertEquals(4000.1, parsedNumber);
assertEquals(4000.1, parsedNumber.doubleValue(), 0);
assertEquals(4000, parsedNumber.intValue());
}
/**
* Converts a string into a number retaining all decimals, and symbols valid in a locale.
* @param number the input string for a number.
* @param locale the locale to consider while parsing a number.
* @return the generic number object which can represent multiple number types.
* @throws ParseException when input contains invalid characters.
*/
private Number parseNumberWithLocale(String number, Locale locale) throws ParseException {
locale = locale == null ? Locale.getDefault() : locale;
NumberFormat numberFormat = NumberFormat.getInstance(locale);
return numberFormat.parse(number);
}
}

View File

@ -40,3 +40,4 @@
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [List Files in a Directory in Java](https://www.baeldung.com/java-list-directory-files)
- [Java InputStream to Byte Array and ByteBuffer](https://www.baeldung.com/convert-input-stream-to-array-of-bytes)
- [Introduction to the Java NIO Selector](https://www.baeldung.com/java-nio-selector)

View File

@ -4,3 +4,5 @@
### Relevant Articles:
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)

View File

@ -0,0 +1,3 @@
## Relevant Articles
- [Void Type in Java](https://www.baeldung.com/java-void-type)

View File

@ -51,3 +51,4 @@
- [Java Bitwise Operators](https://www.baeldung.com/java-bitwise-operators)
- [Guide to Creating and Running a Jar File in Java](https://www.baeldung.com/java-create-jar)
- [Making a JSON POST Request With HttpURLConnection](https://www.baeldung.com/httpurlconnection-post)
- [Convert Hex to ASCII in Java](https://www.baeldung.com/java-convert-hex-to-ascii)

View File

@ -454,7 +454,7 @@
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.5</commons-lang3.version>
<commons-lang3.version>3.9</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>

View File

@ -30,7 +30,7 @@ public class RootCauseFinder {
private AgeCalculator() {
}
public static int calculateAge(String birthDate) throws CalculationException {
public static int calculateAge(String birthDate) {
if (birthDate == null || birthDate.isEmpty()) {
throw new IllegalArgumentException();
}
@ -44,7 +44,7 @@ public class RootCauseFinder {
}
}
private static LocalDate parseDate(String birthDateAsString) throws DateParseException {
private static LocalDate parseDate(String birthDateAsString) {
LocalDate birthDate;
try {
@ -62,14 +62,14 @@ public class RootCauseFinder {
}
static class CalculationException extends Exception {
static class CalculationException extends RuntimeException {
CalculationException(DateParseException ex) {
super(ex);
}
}
static class DateParseException extends Exception {
static class DateParseException extends RuntimeException {
DateParseException(String input) {
super(input);

View File

@ -15,6 +15,7 @@
<modules>
<module>pre-jpms</module>
<module>core-java-exceptions</module>
</modules>
</project>

View File

@ -0,0 +1,3 @@
## Relevant Articles
- [Java 9 Migration Issues and Resolutions](https://www.baeldung.com/java-9-migration-issue)

View File

@ -1,492 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.unix4j</groupId>
<artifactId>unix4j-command</artifactId>
<version>${unix4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>${javamoney.moneta.version}</version>
</dependency>
<dependency>
<groupId>org.owasp.esapi</groupId>
<artifactId>esapi</artifactId>
<version>${esapi.version}</version>
</dependency>
<dependency>
<groupId>com.sun.messaging.mq</groupId>
<artifactId>fscontext</artifactId>
<version>${fscontext.version}</version>
</dependency>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<!-- instrumentation -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javaassist.version}</version>
</dependency>
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>${sun.tools.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>
</dependencies>
<build>
<finalName>core-java</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${maven-jar-plugin.version}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
<archive>
<manifest>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven-shade-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>${onejar-maven-plugin.version}</version>
<executions>
<execution>
<configuration>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
<attachToBuild>true</attachToBuild>
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<classifier>spring-boot</classifier>
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<configuration>
<executable>java</executable>
<mainClass>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</mainClass>
<arguments>
<argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument>
<classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>${maven-javadoc-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<include>**/*IntTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
<executions>
<execution>
<id>run-benchmarks</id>
<!-- <phase>integration-test</phase> -->
<phase>none</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<classpathScope>test</classpathScope>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- java instrumentation profiles to build jars -->
<profile>
<id>buildAgentLoader</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agentLoader</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/AgentLoader.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildApplication</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>application</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/application/MyAtm.class</include>
<include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>buildAgent</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>agent</classifier>
<classesDirectory>target/classes</classesDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
<includes>
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- marshalling -->
<gson.version>2.8.2</gson.version>
<!-- util -->
<commons-lang3.version>3.9</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<commons-math3.version>3.6.1</commons-math3.version>
<decimal4j.version>1.0.3</decimal4j.version>
<unix4j.version>0.4</unix4j.version>
<grep4j.version>1.8.7</grep4j.version>
<fscontext.version>4.6-b01</fscontext.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<!-- maven plugins -->
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
<onejar-maven-plugin.version>1.4.4</onejar-maven-plugin.version>
<maven-shade-plugin.version>3.1.1</maven-shade-plugin.version>
<spring-boot-maven-plugin.version>2.0.3.RELEASE</spring-boot-maven-plugin.version>
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
<icu4j.version>61.1</icu4j.version>
<!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version>
<sun.tools.version>1.8.0</sun.tools.version>
</properties>
</project>

View File

@ -6,4 +6,5 @@
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
- [Kotlin Annotations](https://www.baeldung.com/kotlin-annotations)
- [Split a List into Parts in Kotlin](https://www.baeldung.com/kotlin-split-list-into-parts)
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
- [String Comparison in Kotlin](https://www.baeldung.com/kotlin-string-comparison)
- [Guide to JVM Platform Annotations in Kotlin](https://www.baeldung.com/kotlin-jvm-annotations)

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Guide to Guava Multiset](https://www.baeldung.com/guava-multiset)

View File

@ -7,4 +7,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)

View File

@ -1,2 +1,3 @@
## Relevant Articles:
- [Map of Primitives in Java](https://www.baeldung.com/java-map-primitives)
- [Copying a HashMap in Java](https://www.baeldung.com/java-copy-hashmap)

View File

@ -1,2 +1,3 @@
## Relevant Articles:
- [Converting Between LocalDate and XMLGregorianCalendar](https://www.baeldung.com/java-localdate-to-xmlgregoriancalendar)
- [Convert Time to Milliseconds in Java](https://www.baeldung.com/java-time-milliseconds)

4
java-strings-2/README.MD Normal file
View File

@ -0,0 +1,4 @@
## Relevant Articles
- [Java Localization Formatting Messages](https://www.baeldung.com/java-localization-messages-formatting)
- [Check If a String Contains a Substring](https://www.baeldung.com/java-string-contains-substring)

View File

@ -0,0 +1,28 @@
package com.baeldung.singleton;
public class Car {
private String type;
private String model;
private boolean serviced = false;
public Car(String type, String model) {
super();
this.type = type;
this.model = model;
}
public boolean isServiced () {
return serviced;
}
public void setServiced(Boolean serviced) {
this.serviced = serviced;
}
@Override
public String toString() {
return "Car [type=" + type + ", model=" + model + "]";
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.singleton;
import java.util.UUID;
import javax.enterprise.context.Dependent;
import org.springframework.web.context.annotation.RequestScope;
@RequestScope
public class CarServiceBean {
private UUID id = UUID.randomUUID();
public UUID getId() {
return this.id;
}
@Override
public String toString() {
return "CarService [id=" + id + "]";
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.singleton;
import java.util.UUID;
import javax.ejb.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class CarServiceEjbSingleton {
private static Logger LOG = LoggerFactory.getLogger(CarServiceEjbSingleton.class);
private UUID id = UUID.randomUUID();
private static int serviceQueue;
public UUID getId() {
return this.id;
}
@Override
public String toString() {
return "CarServiceEjbSingleton [id=" + id + "]";
}
public int service(Car car) {
serviceQueue++;
LOG.info("Car {} is being serviced @ CarServiceEjbSingleton - serviceQueue: {}", car, serviceQueue);
simulateService(car);
serviceQueue--;
LOG.info("Car service for {} is completed - serviceQueue: {}", car, serviceQueue);
return serviceQueue;
}
private void simulateService(Car car) {
try {
Thread.sleep(100);
car.setServiced(true);
} catch (InterruptedException e) {
LOG.error("CarServiceEjbSingleton::InterruptedException: {}", e);
}
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.singleton;
import java.util.UUID;
import javax.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class CarServiceSingleton {
private static Logger LOG = LoggerFactory.getLogger(CarServiceSingleton.class);
private UUID id = UUID.randomUUID();
private static int serviceQueue;
public UUID getId() {
return this.id;
}
@Override
public String toString() {
return "CarServiceSingleton [id=" + id + "]";
}
public int service(Car car) {
serviceQueue++;
LOG.info("Car {} is being serviced @ CarServiceSingleton - serviceQueue: {}", car, serviceQueue);
simulateService(car);
serviceQueue--;
LOG.info("Car service for {} is completed - serviceQueue: {}", car, serviceQueue);
return serviceQueue;
}
private void simulateService(Car car) {
try {
Thread.sleep(100);
car.setServiced(true);
} catch (InterruptedException e) {
LOG.error("CarServiceSingleton::InterruptedException: {}", e);
}
}
}

View File

@ -0,0 +1,142 @@
package com.baeldung.singleton;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.ejb.EJB;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CarServiceIntegrationTest {
public static final Logger LOG = LoggerFactory.getLogger(CarServiceIntegrationTest.class);
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(CarServiceBean.class, CarServiceSingleton.class, CarServiceEjbSingleton.class, Car.class)
.addAsResource("META-INF/persistence.xml")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Inject
private CarServiceBean carServiceBean;
@Inject
private CarServiceSingleton carServiceSingleton;
@EJB
private CarServiceEjbSingleton carServiceEjbSingleton;
private static Map<String, UUID> idMap = new HashMap<>();
@Before
public void setUp() {
// populate idMap only on first run
if (idMap.isEmpty()) {
LOG.info("setUp::carServiceBean: {}", carServiceBean.getId());
idMap.put("carServiceBeanId", carServiceBean.getId());
LOG.info("setUp::carServiceSingleton: {}", carServiceSingleton.getId());
idMap.put("carServiceSingletonId", carServiceSingleton.getId());
LOG.info("setUp::carServiceEjbSingleton: {}", carServiceEjbSingleton.getId());
idMap.put("carServiceEjbSingletonId", carServiceEjbSingleton.getId());
}
}
@Test
public void givenRun1_whenGetId_thenSingletonIdEqual() {
int testRun = 1;
assertNotNull(carServiceBean);
assertNotNull(carServiceSingleton);
assertNotNull(carServiceEjbSingleton);
UUID carServiceBeanId = carServiceBean.getId();
assertEquals(idMap.get("carServiceBeanId"), carServiceBeanId);
LOG.info("Test run {}::carServiceBeanId: {}", testRun, carServiceBeanId);
UUID carServiceSingletonId = carServiceSingleton.getId();
assertEquals(idMap.get("carServiceSingletonId"), carServiceSingletonId);
LOG.info("Test run {}::carServiceSingletonId: {}", testRun, carServiceSingletonId);
UUID carServiceEjbSingletonId = carServiceEjbSingleton.getId();
assertEquals(idMap.get("carServiceEjbSingletonId"), carServiceEjbSingletonId);
LOG.info("Test run {}::carServiceEjbSingletonId: {}", testRun, carServiceEjbSingletonId);
}
@Test
public void givenRun2_whenGetId_thenSingletonIdEqual() {
int testRun = 2;
assertNotNull(carServiceBean);
assertNotNull(carServiceSingleton);
assertNotNull(carServiceEjbSingleton);
UUID carServiceBeanId = carServiceBean.getId();
assertNotEquals(idMap.get("carServiceBeanId"), carServiceBeanId);
LOG.info("Test run {}::carServiceBeanId: {}", testRun, carServiceBeanId);
UUID carServiceSingletonId = carServiceSingleton.getId();
assertEquals(idMap.get("carServiceSingletonId"), carServiceSingletonId);
LOG.info("Test run {}::carServiceSingletonId: {}", testRun, carServiceSingletonId);
UUID carServiceEjbSingletonId = carServiceEjbSingleton.getId();
assertEquals(idMap.get("carServiceEjbSingletonId"), carServiceEjbSingletonId);
LOG.info("Test run {}::carServiceEjbSingletonId: {}", testRun, carServiceEjbSingletonId);
}
@Test
public void givenRun3_whenSingleton_thenNoLocking() {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
String model = Double.toString(Math.round(Math.random() * 100));
Car car = new Car("Speedster", model);
int serviceQueue = carServiceSingleton.service(car);
assertTrue(serviceQueue < 10);
}
}).start();
}
return;
}
@Test
public void givenRun4_whenEjb_thenLocking() {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
String model = Double.toString(Math.round(Math.random() * 100));
Car car = new Car("Speedster", model);
int serviceQueue = carServiceEjbSingleton.service(car);
assertEquals(0, serviceQueue);
}
}).start();
}
return;
}
}

3
jhipster-5/README.md Normal file
View File

@ -0,0 +1,3 @@
## Relevant articles:
- [Creating New APIs and Views in JHipster](https://www.baeldung.com/jhipster-new-apis-and-views)

View File

@ -7,6 +7,7 @@ version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.41'
ext.ktor_version = '0.9.2'
ext.khttp_version = '0.1.0'
repositories {
mavenCentral()
@ -47,11 +48,16 @@ dependencies {
compile "io.ktor:ktor-server-netty:$ktor_version"
compile "ch.qos.logback:logback-classic:1.2.1"
compile "io.ktor:ktor-gson:$ktor_version"
compile "khttp:khttp:$khttp_version"
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.jetbrains.spek', name: 'spek-api', version: '1.1.5'
testCompile group: 'org.jetbrains.spek', name: 'spek-subject-extension', version: '1.1.5'
testCompile group: 'org.jetbrains.spek', name: 'spek-junit-platform-engine', version: '1.1.5'
implementation 'com.beust:klaxon:3.0.1'
implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
}
task runServer(type: JavaExec) {
main = 'APIServer'
classpath = sourceSets.main.runtimeClasspath
}
}

View File

@ -166,6 +166,12 @@
<version>2.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxkotlin</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,157 @@
package com.baeldung.kotlin.rxkotlin
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import io.reactivex.rxkotlin.*
import io.reactivex.subjects.PublishSubject
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
class RxKotlinTest {
@Test
fun whenBooleanArrayToObserver_thenBooleanObserver() {
val observable = listOf(true, false, false).toObservable()
observable.test().assertValues(true, false, false)
}
@Test
fun whenBooleanArrayToFlowable_thenBooleanFlowable() {
val flowable = listOf(true, false, false).toFlowable()
flowable.buffer(2).test().assertValues(listOf(true, false), listOf(false))
}
@Test
fun whenIntArrayToObserver_thenIntObserver() {
val observable = listOf(1, 1, 2, 3).toObservable()
observable.test().assertValues(1, 1, 2, 3)
}
@Test
fun whenIntArrayToFlowable_thenIntFlowable() {
val flowable = listOf(1, 1, 2, 3).toFlowable()
flowable.buffer(2).test().assertValues(listOf(1, 1), listOf(2, 3))
}
@Test
fun whenObservablePairToMap_thenSingleNoDuplicates() {
val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
val observable = list.toObservable()
val map = observable.toMap()
assertEquals(mapOf(Pair("a", 4), Pair("b", 2), Pair("c", 3)), map.blockingGet())
}
@Test
fun whenObservablePairToMap_thenSingleWithDuplicates() {
val list = listOf(Pair("a", 1), Pair("b", 2), Pair("c", 3), Pair("a", 4))
val observable = list.toObservable()
val map = observable.toMultimap()
assertEquals(
mapOf(Pair("a", listOf(1, 4)), Pair("b", listOf(2)), Pair("c", listOf(3))),
map.blockingGet())
}
@Test
fun whenMergeAll_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.mergeAll()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenConcatAll_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.concatAll()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenSwitchLatest_thenStream() {
val subject = PublishSubject.create<Observable<String>>()
val observable = subject.switchLatest()
val testObserver = observable.test()
subject.onNext(Observable.just("first", "second"))
testObserver.assertValues("first", "second")
subject.onNext(Observable.just("third", "fourth"))
subject.onNext(Observable.just("fifth"))
testObserver.assertValues("first", "second", "third", "fourth", "fifth")
}
@Test
fun whenMergeAllMaybes_thenObservable() {
val subject = PublishSubject.create<Maybe<Int>>()
val observable = subject.mergeAllMaybes()
val testObserver = observable.test()
subject.onNext(Maybe.just(1))
subject.onNext(Maybe.just(2))
subject.onNext(Maybe.empty())
testObserver.assertValues(1, 2)
subject.onNext(Maybe.error(Exception("")))
subject.onNext(Maybe.just(3))
testObserver.assertValues(1, 2).assertError(Exception::class.java)
}
@Test
fun whenMerge_thenStream() {
val observables = mutableListOf(Observable.just("first", "second"))
val observable = observables.merge()
observables.add(Observable.just("third", "fourth"))
observables.add(Observable.error(Exception("e")))
observables.add(Observable.just("fifth"))
observable.test().assertValues("first", "second", "third", "fourth").assertError(Exception::class.java)
}
@Test
fun whenMergeDelayError_thenStream() {
val observables = mutableListOf<Observable<String>>(Observable.error(Exception("e1")))
val observable = observables.mergeDelayError()
observables.add(Observable.just("1", "2"))
observables.add(Observable.error(Exception("e2")))
observables.add(Observable.just("3"))
observable.test().assertValues("1", "2", "3").assertError(Exception::class.java)
}
@Test
fun whenCast_thenUniformType() {
val observable = Observable.just<Number>(1, 1, 2, 3)
observable.cast<Int>().test().assertValues(1, 1, 2, 3)
}
@Test
fun whenOfType_thenFilter() {
val observable = Observable.just(1, "and", 2, "and")
observable.ofType<Int>().test().assertValues(1, 2)
}
@Test
fun whenFunction_thenCompletable() {
var value = 0
val completable = { value = 3 }.toCompletable()
assertFalse(completable.test().isCancelled)
assertEquals(3, value)
}
@Test
fun whenHelper_thenMoreIdiomaticKotlin() {
val zipWith = Observable.just(1).zipWith(Observable.just(2)) { a, b -> a + b }
zipWith.subscribeBy(onNext = { println(it) })
val zip = Observables.zip(Observable.just(1), Observable.just(2)) { a, b -> a + b }
zip.subscribeBy(onNext = { println(it) })
val zipOrig = Observable.zip(Observable.just(1), Observable.just(2), BiFunction<Int, Int, Int> { a, b -> a + b })
zipOrig.subscribeBy(onNext = { println(it) })
}
}

View File

@ -1,3 +1,7 @@
## Relevant Articles
### Relevant Articles:
- [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java)
- [Guide to Classgraph Library](https://www.baeldung.com/classgraph)
- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program)

View File

@ -1,3 +1,4 @@
### Relevant Articles:
- [Get Log Output in JSON](https://www.baeldung.com/java-log-json-output)
- [SLF4J Warning: Class Path Contains Multiple SLF4J Bindings](https://www.baeldung.com/slf4j-classpath-multiple-bindings)

View File

@ -5,7 +5,6 @@
### Relevant Articles:
- [Introduction to Hibernate Search](http://www.baeldung.com/hibernate-search)
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
- [Introduction to Lettuce the Java Redis Client](http://www.baeldung.com/java-redis-lettuce)
- [A Guide to Jdbi](http://www.baeldung.com/jdbi)
- [Pessimistic Locking in JPA](http://www.baeldung.com/jpa-pessimistic-locking)
@ -13,3 +12,6 @@
- [Spring Data with Reactive Cassandra](https://www.baeldung.com/spring-data-cassandra-reactive)
- [Spring Data JPA Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
- [Difference Between save() and saveAndFlush() in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-save-saveandflush)
- [Spring Boot with Hibernate](https://www.baeldung.com/spring-boot-hibernate)
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)
- [Difference Between @Size, @Length, and @Column(length=value)](https://www.baeldung.com/jpa-size-length-column-differences)

View File

@ -8,3 +8,4 @@
- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [A Simple Guide to Connection Pooling in Java](https://www.baeldung.com/java-connection-pooling)
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
- [Types of SQL Joins](https://www.baeldung.com/sql-joins)

View File

@ -0,0 +1,4 @@
### Relevant Articles:
- [Persisting Maps with Hibernate](https://www.baeldung.com/hibernate-persisting-maps)

View File

@ -2,8 +2,9 @@
- [A Guide to SqlResultSetMapping](http://www.baeldung.com/jpa-sql-resultset-mapping)
- [A Guide to Stored Procedures with JPA](http://www.baeldung.com/jpa-stored-procedures)
- [Fixing the JPA error “java.lang.String cannot be cast to [Ljava.lang.String;”]](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [Fixing the JPA error “java.lang.String cannot be cast to Ljava.lang.String;”](https://www.baeldung.com/jpa-error-java-lang-string-cannot-be-cast)
- [JPA Entity Graph](https://www.baeldung.com/jpa-entity-graph)
- [JPA 2.2 Support for Java 8 Date/Time Types](https://www.baeldung.com/jpa-java-time)
- [Converting Between LocalDate and SQL Date](https://www.baeldung.com/java-convert-localdate-sql-date)
- [Combining JPA And/Or Criteria Predicates](https://www.baeldung.com/jpa-and-or-criteria-predicates)
- [Types of JPA Queries](https://www.baeldung.com/jpa-queries)

View File

@ -0,0 +1,33 @@
package com.baeldung.jpa.basicannotation;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
@Entity
public class Course {
@Id
private int id;
@Basic(optional = false, fetch = FetchType.LAZY)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,91 @@
package com.baeldung.jpa.enums;
import javax.persistence.*;
@Entity
public class Article {
@Id
private int id;
private String title;
@Enumerated(EnumType.ORDINAL)
private Status status;
@Enumerated(EnumType.STRING)
private Type type;
@Basic
private int priorityValue;
@Transient
private Priority priority;
private Category category;
public Article() {
}
@PostLoad
void fillTransient() {
if (priorityValue > 0) {
this.priority = Priority.of(priorityValue);
}
}
@PrePersist
void fillPersistent() {
if (priority != null) {
this.priorityValue = priority.getPriority();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Priority getPriority() {
return priority;
}
public void setPriority(Priority priority) {
this.priority = priority;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.jpa.enums;
import java.util.stream.Stream;
public enum Category {
SPORT("S"), MUSIC("M"), TECHNOLOGY("T");
private String code;
Category(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.jpa.enums;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.stream.Stream;
@Converter(autoApply = true)
public class CategoryConverter implements AttributeConverter<Category, String> {
@Override
public String convertToDatabaseColumn(Category category) {
if (category == null) {
return null;
}
return category.getCode();
}
@Override
public Category convertToEntityAttribute(final String code) {
if (code == null) {
return null;
}
return Stream.of(Category.values())
.filter(c -> c.getCode().equals(code))
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.jpa.enums;
import java.util.stream.Stream;
public enum Priority {
LOW(100), MEDIUM(200), HIGH(300);
private int priority;
private Priority(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
public static Priority of(int priority) {
return Stream.of(Priority.values())
.filter(p -> p.getPriority() == priority)
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.jpa.enums;
public enum Status {
OPEN, REVIEW, APPROVED, REJECTED;
}

View File

@ -0,0 +1,5 @@
package com.baeldung.jpa.enums;
enum Type {
INTERNAL, EXTERNAL;
}

View File

@ -26,6 +26,8 @@
<persistence-unit name="jpa-h2">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.jpa.stringcast.Message</class>
<class>com.baeldung.jpa.enums.Article</class>
<class>com.baeldung.jpa.enums.CategoryConverter</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
@ -146,4 +148,4 @@
</properties>
</persistence-unit>
</persistence>
</persistence>

View File

@ -0,0 +1,56 @@
package com.baeldung.jpa.basicannotation;
import org.hibernate.PropertyValueException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import java.io.IOException;
public class BasicAnnotationIntegrationTest {
private static EntityManager entityManager;
private static EntityManagerFactory entityManagerFactory;
@BeforeClass
public void setup() {
entityManagerFactory = Persistence.createEntityManagerFactory("java-jpa-scheduled-day");
entityManager = entityManagerFactory.createEntityManager();
}
@Test
public void givenACourse_whenCourseNamePresent_shouldPersist() {
Course course = new Course();
course.setName("Computers");
entityManager.persist(course);
entityManager.flush();
entityManager.clear();
}
@Test(expected = PropertyValueException.class)
public void givenACourse_whenCourseNameAbsent_shouldFail() {
Course course = new Course();
entityManager.persist(course);
entityManager.flush();
entityManager.clear();
}
@AfterClass
public void destroy() {
if (entityManager != null) {
entityManager.close();
}
if (entityManagerFactory != null) {
entityManagerFactory.close();
}
}
}

View File

@ -0,0 +1,118 @@
package com.baeldung.jpa.enums;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArticleUnitTest {
private static EntityManager em;
private static EntityManagerFactory emFactory;
@BeforeClass
public static void setup() {
Map properties = new HashMap();
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
emFactory = Persistence.createEntityManagerFactory("jpa-h2", properties);
em = emFactory.createEntityManager();
}
@Test
public void shouldPersistStatusEnumOrdinalValue() {
// given
Article article = new Article();
article.setId(1);
article.setTitle("ordinal title");
article.setStatus(Status.OPEN);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 1);
assertEquals(1, persistedArticle.getId());
assertEquals("ordinal title", persistedArticle.getTitle());
assertEquals(Status.OPEN, persistedArticle.getStatus());
}
@Test
public void shouldPersistTypeEnumStringValue() {
// given
Article article = new Article();
article.setId(2);
article.setTitle("string title");
article.setType(Type.EXTERNAL);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 2);
assertEquals(2, persistedArticle.getId());
assertEquals("string title", persistedArticle.getTitle());
assertEquals(Type.EXTERNAL, persistedArticle.getType());
}
@Test
public void shouldPersistPriorityIntValue() {
// given
Article article = new Article();
article.setId(3);
article.setTitle("callback title");
article.setPriority(Priority.HIGH);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 3);
assertEquals(3, persistedArticle.getId());
assertEquals("callback title", persistedArticle.getTitle());
assertEquals(Priority.HIGH, persistedArticle.getPriority());
}
@Test
public void shouldPersistCategoryEnumConvertedValue() {
// given
Article article = new Article();
article.setId(4);
article.setTitle("converted title");
article.setCategory(Category.MUSIC);
// when
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(article);
tx.commit();
// then
Article persistedArticle = em.find(Article.class, 4);
assertEquals(4, persistedArticle.getId());
assertEquals("converted title", persistedArticle.getTitle());
assertEquals(Category.MUSIC, persistedArticle.getCategory());
}
}

View File

@ -2,3 +2,4 @@
- [A Guide to MongoDB with Java](http://www.baeldung.com/java-mongodb)
- [A Simple Tagging Implementation with MongoDB](http://www.baeldung.com/mongodb-tagging)
- [MongoDB BSON Guide](https://www.baeldung.com/mongodb-bson)

View File

@ -55,5 +55,6 @@
<module>spring-hibernate-5</module>
<module>spring-hibernate4</module>
<module>spring-jpa</module>
<module>spring-persistence-simple</module>
</modules>
</project>

View File

@ -1,6 +1,14 @@
=========
## Spring Data JPA Example Project
### Relevant Articles:
- [Spring Data JPA Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
=========
## Spring Data JPA Example Project
### Relevant Articles:
- [Spring Data JPA Derived Delete Methods](https://www.baeldung.com/spring-data-jpa-deleteby)
- [JPA Join Types](https://www.baeldung.com/jpa-join-types)
- [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries)
- [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query)
- [Spring Data JPA Repository Populators](https://www.baeldung.com/spring-data-jpa-repository-populators)
- [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters)
- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections)
- [JPA @Embedded And @Embeddable](https://www.baeldung.com/jpa-embedded-embeddable)
- [Spring Data JPA Delete and Relationships](https://www.baeldung.com/spring-data-jpa-delete)

View File

@ -0,0 +1,70 @@
package com.baeldung.derivedquery.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.ZonedDateTime;
@Table(name = "users")
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
private ZonedDateTime birthDate;
private Boolean active;
public User() {
}
public User(String name, Integer age, ZonedDateTime birthDate, Boolean active) {
this.name = name;
this.age = age;
this.birthDate = birthDate;
this.active = active;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public ZonedDateTime getBirthDate() {
return birthDate;
}
public void setBirthDate(ZonedDateTime birthDate) {
this.birthDate = birthDate;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.derivedquery.repository;
import com.baeldung.derivedquery.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.List;
public interface UserRepository extends JpaRepository<User, Integer> {
List<User> findByName(String name);
List<User> findByNameIs(String name);
List<User> findByNameEquals(String name);
List<User> findByNameIsNull();
List<User> findByNameNot(String name);
List<User> findByNameIsNot(String name);
List<User> findByNameStartingWith(String name);
List<User> findByNameEndingWith(String name);
List<User> findByNameContaining(String name);
List<User> findByNameLike(String name);
List<User> findByAgeLessThan(Integer age);
List<User> findByAgeLessThanEqual(Integer age);
List<User> findByAgeGreaterThan(Integer age);
List<User> findByAgeGreaterThanEqual(Integer age);
List<User> findByAgeBetween(Integer startAge, Integer endAge);
List<User> findByBirthDateAfter(ZonedDateTime birthDate);
List<User> findByBirthDateBefore(ZonedDateTime birthDate);
List<User> findByActiveTrue();
List<User> findByActiveFalse();
List<User> findByAgeIn(Collection<Integer> ages);
List<User> findByNameOrBirthDate(String name, ZonedDateTime birthDate);
List<User> findByNameOrBirthDateAndActive(String name, ZonedDateTime birthDate, Boolean active);
List<User> findByNameOrderByName(String name);
List<User> findByNameOrderByNameDesc(String name);
}

View File

@ -0,0 +1,172 @@
package com.baeldung.derivedquery.repository;
import com.baeldung.Application;
import com.baeldung.derivedquery.entity.User;
import com.baeldung.derivedquery.repository.UserRepository;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
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.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class UserRepositoryTest {
private static final String USER_NAME_ADAM = "Adam";
private static final String USER_NAME_EVE = "Eve";
private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now();
@Autowired
private UserRepository userRepository;
@Before
public void setUp() {
User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true);
User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false);
User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true);
User user4 = new User(null, 30, BIRTHDATE, false);
userRepository.saveAll(Arrays.asList(user1, user2, user3, user4));
}
@After
public void tearDown() {
userRepository.deleteAll();
}
@Test
public void whenFindByName_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size());
}
@Test
public void whenFindByNameIsNull_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameIsNull().size());
}
@Test
public void whenFindByNameNot_thenReturnsCorrectResult() {
assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName());
}
@Test
public void whenFindByNameStartingWith_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByNameStartingWith("A").size());
}
@Test
public void whenFindByNameEndingWith_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameEndingWith("e").size());
}
@Test
public void whenByNameContaining_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByNameContaining("v").size());
}
@Test
public void whenByNameLike_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByNameEndingWith("%d%m").size());
}
@Test
public void whenByAgeLessThan_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByAgeLessThan(25).size());
}
@Test
public void whenByAgeLessThanEqual_thenReturnsCorrectResult() {
assertEquals(3, userRepository.findByAgeLessThanEqual(25).size());
}
@Test
public void whenByAgeGreaterThan_thenReturnsCorrectResult() {
assertEquals(1, userRepository.findByAgeGreaterThan(25).size());
}
@Test
public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size());
}
@Test
public void whenByAgeBetween_thenReturnsCorrectResult() {
assertEquals(4, userRepository.findByAgeBetween(20, 30).size());
}
@Test
public void whenByBirthDateAfter_thenReturnsCorrectResult() {
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size());
}
@Test
public void whenByBirthDateBefore_thenReturnsCorrectResult() {
final ZonedDateTime yesterday = BIRTHDATE.minusDays(1);
assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size());
}
@Test
public void whenByActiveTrue_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByActiveTrue().size());
}
@Test
public void whenByActiveFalse_thenReturnsCorrectResult() {
assertEquals(2, userRepository.findByActiveFalse().size());
}
@Test
public void whenByAgeIn_thenReturnsCorrectResult() {
final List<Integer> ages = Arrays.asList(20, 25);
assertEquals(3, userRepository.findByAgeIn(ages).size());
}
@Test
public void whenByNameOrBirthDate() {
assertEquals(4, userRepository.findByNameOrBirthDate(USER_NAME_ADAM, BIRTHDATE).size());
}
@Test
public void whenByNameOrBirthDateAndActive() {
assertEquals(3, userRepository.findByNameOrBirthDateAndActive(USER_NAME_ADAM, BIRTHDATE, false).size());
}
@Test
public void whenByNameOrderByName() {
assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size());
}
}

View File

@ -6,7 +6,6 @@
- [Spring JPA Multiple Databases](http://www.baeldung.com/spring-data-jpa-multiple-databases)
- [Spring Data JPA Adding a Method in All Repositories](http://www.baeldung.com/spring-data-jpa-method-in-all-repositories)
- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
- [Spring Data Annotations](http://www.baeldung.com/spring-data-annotations)
- [Spring Data Java 8 Support](http://www.baeldung.com/spring-data-java-8)
- [A Simple Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging)

View File

@ -4,7 +4,6 @@
### Relevant Articles:
- [Guide to Hibernate 4 with Spring](http://www.baeldung.com/hibernate-4-spring)
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
- [Hibernate Pagination](http://www.baeldung.com/hibernate-pagination)
- [Sorting with Hibernate](http://www.baeldung.com/hibernate-sort)
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)

View File

@ -4,8 +4,6 @@
### Relevant Articles:
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [The DAO with JPA and Spring](http://www.baeldung.com/spring-dao-jpa)
- [JPA Pagination](http://www.baeldung.com/jpa-pagination)
- [Sorting with JPA](http://www.baeldung.com/jpa-sort)

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,24 @@
=========
## Spring Persistence Example Project
### Relevant Articles:
- [A Guide to JPA with Spring](https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa)
- [Bootstrapping Hibernate 5 with Spring](http://www.baeldung.com/hibernate-5-spring)
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
- [DAO with Spring and Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
- [Transactions with Spring and JPA](https://www.baeldung.com/transaction-configuration-with-jpa-and-spring)
- [Introduction to Spring Data JPA](http://www.baeldung.com/the-persistence-layer-with-spring-data-jpa)
- [Spring Data JPA @Query](http://www.baeldung.com/spring-data-jpa-query)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
"No persistence xml file found in project"
This can be ignored:
- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project"
Or:
- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator

View File

@ -0,0 +1,160 @@
<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>spring-persistence-simple</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-persistence-simple</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- persistence -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>${jta.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring-data-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>${tomcat-dbcp.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
<build>
<finalName>spring-persistence-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>5.1.6.RELEASE</org.springframework.version>
<!-- persistence -->
<hibernate.version>5.4.2.Final</hibernate.version>
<mysql-connector-java.version>6.0.6</mysql-connector-java.version>
<spring-data-jpa.version>2.1.6.RELEASE</spring-data-jpa.version>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version>
<querydsl.version>4.2.1</querydsl.version>
<!-- util -->
<guava.version>21.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<assertj.version>3.8.0</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,39 @@
package com.baeldung.hibernate.bootstrap;
import com.baeldung.hibernate.bootstrap.model.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class BarHibernateDAO {
@Autowired
private SessionFactory sessionFactory;
public TestEntity findEntity(int id) {
return getCurrentSession().find(TestEntity.class, 1);
}
public void createEntity(TestEntity entity) {
getCurrentSession().save(entity);
}
public void createEntity(int id, String newDescription) {
TestEntity entity = findEntity(id);
entity.setDescription(newDescription);
getCurrentSession().save(entity);
}
public void deleteEntity(int id) {
TestEntity entity = findEntity(id);
getCurrentSession().delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.hibernate.bootstrap;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
public class HibernateConf {
@Autowired
private Environment env;
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
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"));
return hibernateProperties;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.hibernate.bootstrap;
import com.google.common.base.Preconditions;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:hibernate5Configuration.xml" })
public class HibernateXMLConf {
}

View File

@ -0,0 +1,29 @@
package com.baeldung.hibernate.bootstrap.model;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class TestEntity {
private int id;
private String description;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.persistence.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,60 @@
package com.baeldung.persistence.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()).list();
}
@Override
public T create(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity);
return entity;
}
@Override
public T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
}
@Override
public void delete(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity);
}
@Override
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}

View File

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

View File

@ -0,0 +1,14 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
import org.baeldung.persistence.dao.AbstractJpaDAO;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
@Repository
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class GenericJpaDao<T extends Serializable> extends AbstractJpaDAO<T> implements IGenericDao<T> {
//
}

View File

@ -0,0 +1,7 @@
package com.baeldung.persistence.dao.common;
import java.io.Serializable;
public interface IGenericDao<T extends Serializable> extends IOperations<T> {
//
}

View File

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

View File

@ -0,0 +1,20 @@
package com.baeldung.persistence.dao.impl;
import org.baeldung.persistence.dao.IFooDao;
import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
import com.baeldung.persistence.dao.common.AbstractHibernateDao;
@Repository
public class FooDao extends AbstractHibernateDao<Foo> implements IFooDao {
public FooDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@ -0,0 +1,118 @@
package org.baeldung.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.baeldung.persistence.dao.IFooDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.baeldung.persistence.dao.impl.FooDao;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.baeldung.persistence" }, transactionManagerRef = "jpaTransactionManager")
@EnableJpaAuditing
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "com.baeldung.persistence" })
public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(restDataSource());
emf.setPackagesToScan(new String[] { "com.baeldung.persistence.model" });
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaProperties(hibernateProperties());
return emf;
}
@Bean
public DataSource restDataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PlatformTransactionManager jpaTransactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
public IFooDao fooHibernateDao() {
return new FooDao();
}
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", "true");
// hibernateProperties.setProperty("hibernate.format_sql", "true");
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
// Envers properties
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix"));
return hibernateProperties;
}
}

View File

@ -0,0 +1,87 @@
package org.baeldung.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
@ComponentScan({ "org.baeldung.persistence" })
@EnableJpaRepositories(basePackages = "org.baeldung.persistence.dao")
public class PersistenceJPAConfig {
@Autowired
private Environment env;
public PersistenceJPAConfig() {
super();
}
// beans
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.cache.use_second_level_cache", "false");
return hibernateProperties;
}
}

View File

@ -0,0 +1,47 @@
package org.baeldung.persistence.dao;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public abstract class AbstractJpaDAO<T extends Serializable> {
private Class<T> clazz;
@PersistenceContext
private EntityManager entityManager;
public final void setClazz(final Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
public T findOne(final long id) {
return entityManager.find(clazz, id);
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return entityManager.createQuery("from " + clazz.getName()).getResultList();
}
public T create(final T entity) {
entityManager.persist(entity);
return entity;
}
public T update(final T entity) {
return entityManager.merge(entity);
}
public void delete(final T entity) {
entityManager.remove(entity);
}
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
delete(entity);
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung.persistence.dao;
import org.baeldung.persistence.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooDao extends AbstractJpaDAO<Foo> implements IFooDao {
public FooDao() {
super();
setClazz(Foo.class);
}
// API
}

View File

@ -0,0 +1,21 @@
package org.baeldung.persistence.dao;
import java.util.List;
import org.baeldung.persistence.model.Foo;
public interface IFooDao {
Foo findOne(long id);
List<Foo> findAll();
Foo create(Foo entity);
Foo update(Foo entity);
void delete(Foo entity);
void deleteById(long entityId);
}

View File

@ -0,0 +1,102 @@
package org.baeldung.persistence.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
@Entity
public class Bar implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "bar", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@OrderBy("name ASC")
List<Foo> fooList;
public Bar() {
super();
}
public Bar(final String name) {
super();
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<Foo> getFooList() {
return fooList;
}
public void setFooList(final List<Foo> fooList) {
this.fooList = fooList;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Bar [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,104 @@
package org.baeldung.persistence.model;
import java.io.Serializable;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@NamedNativeQueries({ @NamedNativeQuery(name = "callGetAllFoos", query = "CALL GetAllFoos()", resultClass = Foo.class), @NamedNativeQuery(name = "callGetFoosByName", query = "CALL GetFoosByName(:fooName)", resultClass = Foo.class) })
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Column(name = "NAME")
private String name;
@ManyToOne(targetEntity = Bar.class, fetch = FetchType.EAGER)
@JoinColumn(name = "BAR_ID")
private Bar bar;
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,36 @@
package org.baeldung.persistence.service;
import java.util.List;
import org.baeldung.persistence.dao.IFooDao;
import org.baeldung.persistence.model.Foo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class FooService {
@Autowired
private IFooDao dao;
public FooService() {
super();
}
// API
public void create(final Foo entity) {
dao.create(entity);
}
public Foo findOne(final long id) {
return dao.findOne(id);
}
public List<Foo> findAll() {
return dao.findAll();
}
}

View File

@ -0,0 +1,85 @@
package org.baeldung.spring.data.persistence.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-${envTarget:h2}.properties" })
@ComponentScan({ "org.baeldung.spring.data.persistence" })
// @ImportResource("classpath*:springDataPersistenceConfig.xml")
@EnableJpaRepositories(basePackages = "org.baeldung.spring.data.persistence.dao")
public class PersistenceConfig {
@Autowired
private Environment env;
public PersistenceConfig() {
super();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.spring.data.persistence.model" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// vendorAdapter.set
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
return hibernateProperties;
}
}

View File

@ -0,0 +1,11 @@
package org.baeldung.spring.data.persistence.dao;
import org.baeldung.spring.data.persistence.model.Foo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface IFooDao extends JpaRepository<Foo, Long> {
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
}

View File

@ -0,0 +1,98 @@
package org.baeldung.spring.data.persistence.dao.user;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;
import org.baeldung.spring.data.persistence.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface UserRepository extends JpaRepository<User, Integer>, UserRepositoryCustom {
Stream<User> findAllByName(String name);
@Query("SELECT u FROM User u WHERE u.status = 1")
Collection<User> findAllActiveUsers();
@Query("select u from User u where u.email like '%@gmail.com'")
List<User> findUsersWithGmailAddress();
@Query(value = "SELECT * FROM Users u WHERE u.status = 1", nativeQuery = true)
Collection<User> findAllActiveUsersNative();
@Query("SELECT u FROM User u WHERE u.status = ?1")
User findUserByStatus(Integer status);
@Query(value = "SELECT * FROM Users u WHERE u.status = ?1", nativeQuery = true)
User findUserByStatusNative(Integer status);
@Query("SELECT u FROM User u WHERE u.status = ?1 and u.name = ?2")
User findUserByStatusAndName(Integer status, String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByStatusAndNameNamedParams(@Param("status") Integer status, @Param("name") String name);
@Query(value = "SELECT * FROM Users u WHERE u.status = :status AND u.name = :name", nativeQuery = true)
User findUserByStatusAndNameNamedParamsNative(@Param("status") Integer status, @Param("name") String name);
@Query("SELECT u FROM User u WHERE u.status = :status and u.name = :name")
User findUserByUserStatusAndUserName(@Param("status") Integer userStatus, @Param("name") String userName);
@Query("SELECT u FROM User u WHERE u.name like ?1%")
User findUserByNameLike(String name);
@Query("SELECT u FROM User u WHERE u.name like :name%")
User findUserByNameLikeNamedParam(@Param("name") String name);
@Query(value = "SELECT * FROM users u WHERE u.name LIKE ?1%", nativeQuery = true)
User findUserByNameLikeNative(String name);
@Query(value = "SELECT u FROM User u")
List<User> findAllUsers(Sort sort);
@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true)
Page<User> findAllUsersWithPaginationNative(Pageable pageable);
@Modifying
@Query("update User u set u.status = :status where u.name = :name")
int updateUserSetStatusForName(@Param("status") Integer status, @Param("name") String name);
@Modifying
@Query(value = "UPDATE Users u SET u.status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNative(Integer status, String name);
@Query(value = "INSERT INTO Users (name, age, email, status, active) VALUES (:name, :age, :email, :status, :active)", nativeQuery = true)
@Modifying
void insertUser(@Param("name") String name, @Param("age") Integer age, @Param("email") String email, @Param("status") Integer status, @Param("active") boolean active);
@Modifying
@Query(value = "UPDATE Users u SET status = ? WHERE u.name = ?", nativeQuery = true)
int updateUserSetStatusForNameNativePostgres(Integer status, String name);
@Query(value = "SELECT u FROM User u WHERE u.name IN :names")
List<User> findUserByNameList(@Param("names") Collection<String> names);
void deleteAllByCreationDateAfter(LocalDate date);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("update User u set u.active = false where u.lastLoginDate < :date")
void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date);
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query("delete User u where u.active = false")
int deleteDeactivatedUsers();
@Modifying(clearAutomatically = true, flushAutomatically = true)
@Query(value = "alter table USERS add column deleted int(1) not null default 0", nativeQuery = true)
void addDeletedColumn();
}

View File

@ -0,0 +1,14 @@
package org.baeldung.spring.data.persistence.dao.user;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import org.baeldung.spring.data.persistence.model.User;
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);
List<User> findAllUsersByPredicates(Collection<Predicate<User>> predicates);
}

View File

@ -0,0 +1,57 @@
package org.baeldung.spring.data.persistence.dao.user;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.baeldung.spring.data.persistence.model.User;
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<User> findUserByEmails(Set<String> emails) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> user = query.from(User.class);
Path<String> emailPath = user.get("email");
List<Predicate> predicates = new ArrayList<>();
for (String email : emails) {
predicates.add(cb.like(emailPath, email));
}
query.select(user)
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query)
.getResultList();
}
@Override
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
Stream<User> allUsersStream = allUsers.stream();
for (java.util.function.Predicate<User> predicate : predicates) {
allUsersStream = allUsersStream.filter(predicate);
}
return allUsersStream.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,83 @@
package org.baeldung.spring.data.persistence.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,86 @@
package org.baeldung.spring.data.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Possession {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public Possession() {
super();
}
public Possession(final String name) {
super();
this.name = name;
}
public long getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + (int) (id ^ (id >>> 32));
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Possession other = (Possession) obj;
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,132 @@
package org.baeldung.spring.data.persistence.model;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private LocalDate creationDate;
private LocalDate lastLoginDate;
private boolean active;
private int age;
@Column(unique = true, nullable = false)
private String email;
private Integer status;
@OneToMany
List<Possession> possessionList;
public User() {
super();
}
public User(String name, LocalDate creationDate,String email, Integer status) {
this.name = name;
this.creationDate = creationDate;
this.email = email;
this.status = status;
this.active = true;
}
public int getId() {
return id;
}
public void setId(final int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}

View File

@ -0,0 +1,11 @@
package org.baeldung.spring.data.persistence.service;
import org.baeldung.spring.data.persistence.model.Foo;
import com.baeldung.persistence.dao.common.IOperations;
public interface IFooService extends IOperations<Foo> {
Foo retrieveByName(String name);
}

View File

@ -0,0 +1,56 @@
package org.baeldung.spring.data.persistence.service.common;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import com.baeldung.persistence.dao.common.IOperations;
import com.google.common.collect.Lists;
@Transactional
public abstract class AbstractService<T extends Serializable> implements IOperations<T> {
// read - one
@Override
@Transactional(readOnly = true)
public T findOne(final long id) {
return getDao().findById(id).orElse(null);
}
// read - all
@Override
@Transactional(readOnly = true)
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
// write
@Override
public T create(final T entity) {
return getDao().save(entity);
}
@Override
public T update(final T entity) {
return getDao().save(entity);
}
@Override
public void delete(T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(long entityId) {
T entity = findOne(entityId);
delete(entity);
}
protected abstract PagingAndSortingRepository<T, Long> getDao();
}

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