Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Philippe 2019-05-11 21:17:43 -03:00
commit 2fad9df50c
162 changed files with 3817 additions and 151 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

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

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

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

@ -21,5 +21,14 @@
- [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)

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

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

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

@ -0,0 +1,98 @@
package com.baeldung.exceptions;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeParseException;
import java.util.Objects;
/**
* Utility class to find root cause exceptions.
*/
public class RootCauseFinder {
private RootCauseFinder() {
}
public static Throwable findCauseUsingPlainJava(Throwable throwable) {
Objects.requireNonNull(throwable);
Throwable rootCause = throwable;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
rootCause = rootCause.getCause();
}
return rootCause;
}
/**
* Calculates the age of a person from a given date.
*/
static class AgeCalculator {
private AgeCalculator() {
}
public static int calculateAge(String birthDate) {
if (birthDate == null || birthDate.isEmpty()) {
throw new IllegalArgumentException();
}
try {
return Period
.between(parseDate(birthDate), LocalDate.now())
.getYears();
} catch (DateParseException ex) {
throw new CalculationException(ex);
}
}
private static LocalDate parseDate(String birthDateAsString) {
LocalDate birthDate;
try {
birthDate = LocalDate.parse(birthDateAsString);
} catch (DateTimeParseException ex) {
throw new InvalidFormatException(birthDateAsString, ex);
}
if (birthDate.isAfter(LocalDate.now())) {
throw new DateOutOfRangeException(birthDateAsString);
}
return birthDate;
}
}
static class CalculationException extends RuntimeException {
CalculationException(DateParseException ex) {
super(ex);
}
}
static class DateParseException extends RuntimeException {
DateParseException(String input) {
super(input);
}
DateParseException(String input, Throwable thr) {
super(input, thr);
}
}
static class InvalidFormatException extends DateParseException {
InvalidFormatException(String input, Throwable thr) {
super("Invalid date format: " + input, thr);
}
}
static class DateOutOfRangeException extends DateParseException {
DateOutOfRangeException(String date) {
super("Date out of range: " + date);
}
}
}

View File

@ -0,0 +1,114 @@
package com.baeldung.exceptions;
import com.google.common.base.Throwables;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import static com.baeldung.exceptions.RootCauseFinder.*;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests the {@link RootCauseFinder}.
*/
public class RootCauseFinderUnitTest {
@Test
public void givenBirthDate_whenCalculatingAge_thenAgeReturned() {
try {
int age = AgeCalculator.calculateAge("1990-01-01");
Assertions.assertEquals(1990, LocalDate
.now()
.minus(age, ChronoUnit.YEARS)
.getYear());
} catch (CalculationException e) {
Assertions.fail(e.getMessage());
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingJava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(findCauseUsingPlainJava(ex) instanceof IllegalArgumentException);
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingApacheCommons_thenRootCauseNotFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(ExceptionUtils.getRootCause(ex) instanceof IllegalArgumentException);
}
}
@Test
public void givenWrongFormatDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("010102");
} catch (CalculationException ex) {
assertTrue(Throwables.getRootCause(ex) instanceof DateTimeParseException);
}
}
@Test
public void givenOutOfRangeDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge("2020-04-04");
} catch (CalculationException ex) {
assertTrue(Throwables.getRootCause(ex) instanceof DateOutOfRangeException);
}
}
@Test
public void givenNullDate_whenFindingRootCauseUsingGuava_thenRootCauseFound() {
try {
AgeCalculator.calculateAge(null);
} catch (Exception ex) {
assertTrue(Throwables.getRootCause(ex) instanceof IllegalArgumentException);
}
}
}

View File

@ -15,6 +15,7 @@
<modules>
<module>pre-jpms</module>
<module>core-java-exceptions</module>
</modules>
</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

@ -0,0 +1,21 @@
package com.baeldung.localization;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class App {
/**
* Runs all available formatter
* @throws ParseException
*/
public static void main(String[] args) {
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
Localization.run(locales);
JavaSEFormat.run(locales);
ICUFormat.run(locales);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.localization;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import com.ibm.icu.text.MessageFormat;
public class ICUFormat {
public static String getLabel(Locale locale, Object[] data) {
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
String format = bundle.getString("label-icu");
MessageFormat formatter = new MessageFormat(format, locale);
return formatter.format(data);
}
public static void run(List<Locale> locales) {
System.out.println("ICU formatter");
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.localization;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class JavaSEFormat {
public static String getLabel(Locale locale, Object[] data) {
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
final String pattern = bundle.getString("label");
final MessageFormat formatter = new MessageFormat(pattern, locale);
return formatter.format(data);
}
public static void run(List<Locale> locales) {
System.out.println("Java formatter");
final Date date = new Date(System.currentTimeMillis());
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.localization;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class Localization {
public static String getLabel(Locale locale) {
final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
return bundle.getString("label");
}
public static void run(List<Locale> locales) {
locales.forEach(locale -> System.out.println(getLabel(locale)));
}
}

View File

@ -0,0 +1,2 @@
label=On {0, date, short} {1} has sent you {2, choice, 0#no messages|1#a message|2#two messages|2<{2,number,integer} messages}.
label-icu={0} has sent you {2, plural, =0 {no messages} =1 {a message} other {{2, number, integer} messages}}.

View File

@ -0,0 +1,2 @@
label={0, date, short}, {1}{2, choice, 0# ne|0<} vous a envoy\u00e9 {2, choice, 0#aucun message|1#un message|2#deux messages|2<{2,number,integer} messages}.
label-icu={0} {2, plural, =0 {ne } other {}}vous a envoy\u00e9 {2, plural, =0 {aucun message} =1 {un message} other {{2, number, integer} messages}}.

View File

@ -0,0 +1,2 @@
label={0, date, short} {1} ti ha inviato {2, choice, 0#nessun messagio|1#un messaggio|2#due messaggi|2<{2, number, integer} messaggi}.
label-icu={0} {2, plural, =0 {non } other {}}ti ha inviato {2, plural, =0 {nessun messaggio} =1 {un messaggio} other {{2, number, integer} messaggi}}.

View File

@ -0,0 +1,2 @@
label=W {0, date, short} {1}{2, choice, 0# nie|0<} wys\u0142a\u0142a ci {2, choice, 0#\u017Cadnych wiadomo\u015Bci|1#wiadomo\u015B\u0107|2#dwie wiadomo\u015Bci|2<{2, number, integer} wiadomo\u015Bci}.
label-icu={0} {2, plural, =0 {nie } other {}}{1, select, male {wys\u0142a\u0142} female {wys\u0142a\u0142a} other {wys\u0142a\u0142o}} ci {2, plural, =0 {\u017Cadnej wiadomo\u015Bci} =1 {wiadomo\u015B\u0107} other {{2, number, integer} wiadomo\u015Bci}}.

View File

@ -0,0 +1 @@
label=Alice has sent you a message.

View File

@ -0,0 +1 @@
label=Alice vous a envoy\u00e9 un message.

View File

@ -0,0 +1 @@
label=Alice ti ha inviato un messaggio.

View File

@ -0,0 +1 @@
label=Alice wys\u0142a\u0142a ci wiadomo\u015B\u0107.

View File

@ -0,0 +1,74 @@
package com.baeldung.localization;
import static org.junit.Assert.assertEquals;
import java.util.Locale;
import org.junit.Test;
import com.baeldung.localization.ICUFormat;
public class ICUFormatUnitTest {
@Test
public void givenInUK_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice has sent you no messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInUK_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice has sent you a message.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInUK_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob has sent you 6 messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Bob", "male", 6 }));
}
@Test
public void givenInItaly_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice non ti ha inviato nessun messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInItaly_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice ti ha inviato un messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInItaly_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob ti ha inviato 6 messaggi.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Bob", "male", 6 }));
}
@Test
public void givenInFrance_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice ne vous a envoyé aucun message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInFrance_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice vous a envoyé un message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInFrance_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob vous a envoyé 6 messages.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Bob", "male", 6 }));
}
@Test
public void givenInPoland_whenAliceSendsNothing_thenCorrectMessage() {
assertEquals("Alice nie wysłała ci żadnej wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 0 }));
}
@Test
public void givenInPoland_whenAliceSendsOneMessage_thenCorrectMessage() {
assertEquals("Alice wysłała ci wiadomość.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 1 }));
}
@Test
public void givenInPoland_whenBobSendsSixMessages_thenCorrectMessage() {
assertEquals("Bob wysłał ci 6 wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Bob", "male", 6 }));
}
}

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,6 @@
## 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)

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

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

@ -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,22 @@
=========
## 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)
### 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,131 @@
<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>
</dependencies>
<build>
<finalName>spring-persistence-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</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>
<!-- 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,59 @@
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 void create(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity);
}
@Override
public T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
}
@Override
public void delete(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity);
}
@Override
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
}

View File

@ -0,0 +1,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();
void create(final T entity);
T update(final T entity);
void delete(final T entity);
void deleteById(final long entityId);
}

View File

@ -0,0 +1,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,46 @@
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 void create(final T entity) {
entityManager.persist(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();
void 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,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:persistence-mysql.properties"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.baeldung.persistence.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.eventGeneratedId}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:persistence-h2.properties"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.baeldung.hibernate.bootstrap.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>

View File

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

View File

@ -0,0 +1,13 @@
# jdbc.X
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.user=sa
jdbc.pass=
# hibernate.X
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

View File

@ -0,0 +1,13 @@
# jdbc.X
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate5_01?createDatabaseIfNotExist=true
jdbc.eventGeneratedId=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
# envers.X
envers.audit_table_suffix=_audit_log

View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
>
<context:property-placeholder location="classpath:persistence-h2.properties"/>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="org.baeldung.persistence.model"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!-- <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" /> <property name="generateDdl" value="${jpa.generateDdl}" /> <property name="databasePlatform"
value="${persistence.dialect}" /> </bean> -->
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.pass}"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<tx:annotation-driven/>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>

View File

@ -0,0 +1,20 @@
DELIMITER //
CREATE PROCEDURE GetFoosByName(IN fooName VARCHAR(255))
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
BEGIN
SELECT * FROM foo WHERE name = fooName;
END //
DELIMITER ;
DELIMITER //
CREATE PROCEDURE GetAllFoos()
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY DEFINER
BEGIN
SELECT * FROM foo;
END //
DELIMITER ;

View File

@ -0,0 +1,185 @@
package com.baeldung.hibernate.bootstrap;
import com.baeldung.hibernate.bootstrap.model.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Commit;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.transaction.TestTransaction;
import org.springframework.transaction.annotation.Transactional;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { HibernateConf.class })
@Transactional
public class HibernateBootstrapIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
@Test
public void whenBootstrapHibernateSession_thenNoException() {
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
}
@Test
public void whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
assertTrue(TestTransaction.isActive());
//Save an entity and commit.
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertTrue(TestTransaction.isFlaggedForRollback());
TestTransaction.flagForCommit();
TestTransaction.end();
assertFalse(TestTransaction.isFlaggedForRollback());
assertFalse(TestTransaction.isActive());
//Check that the entity is still there in a new transaction,
//then delete it, but don't commit.
TestTransaction.start();
assertTrue(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
TestTransaction.end();
assertFalse(TestTransaction.isActive());
//Check that the entity is still there in a new transaction,
//then delete it and commit.
TestTransaction.start();
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
assertTrue(TestTransaction.isActive());
TestTransaction.flagForCommit();
TestTransaction.end();
assertFalse(TestTransaction.isActive());
//Check that the entity is no longer there in a new transaction.
TestTransaction.start();
assertTrue(TestTransaction.isActive());
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNull(searchEntity);
}
@Test
@Commit
public void givenTransactionCommitDefault_whenProgrammaticTransactionCommit_thenEntityIsInDatabase() {
assertTrue(TestTransaction.isActive());
//Save an entity and commit.
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
assertFalse(TestTransaction.isFlaggedForRollback());
TestTransaction.end();
assertFalse(TestTransaction.isFlaggedForRollback());
assertFalse(TestTransaction.isActive());
//Check that the entity is still there in a new transaction,
//then delete it, but don't commit.
TestTransaction.start();
assertFalse(TestTransaction.isFlaggedForRollback());
assertTrue(TestTransaction.isActive());
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
TestTransaction.flagForRollback();
TestTransaction.end();
assertFalse(TestTransaction.isActive());
//Check that the entity is still there in a new transaction,
//then delete it and commit.
TestTransaction.start();
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
session.delete(searchEntity);
session.flush();
assertTrue(TestTransaction.isActive());
TestTransaction.end();
assertFalse(TestTransaction.isActive());
//Check that the entity is no longer there in a new transaction.
TestTransaction.start();
assertTrue(TestTransaction.isActive());
session = sessionFactory.getCurrentSession();
searchEntity = session.find(TestEntity.class, 1);
Assert.assertNull(searchEntity);
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.hibernate.bootstrap;
import com.baeldung.hibernate.bootstrap.model.TestEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { HibernateXMLConf.class })
@Transactional
public class HibernateXMLBootstrapIntegrationTest {
@Autowired
private SessionFactory sessionFactory;
@Test
public void whenBootstrapHibernateSession_thenNoException() {
Session session = sessionFactory.getCurrentSession();
TestEntity newEntity = new TestEntity();
newEntity.setId(1);
session.save(newEntity);
TestEntity searchEntity = session.find(TestEntity.class, 1);
Assert.assertNotNull(searchEntity);
}
}

View File

@ -0,0 +1,157 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class FooPaginationPersistenceIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService fooService;
@Before
public final void before() {
final int minimalNumberOfEntities = 25;
if (fooService.findAll().size() <= minimalNumberOfEntities) {
for (int i = 0; i < minimalNumberOfEntities; i++) {
fooService.create(new Foo(randomAlphabetic(6)));
}
}
}
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingFirstPage_thenCorrect() {
final int pageSize = 10;
final Query query = entityManager.createQuery("From Foo");
configurePagination(query, 1, pageSize);
// When
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingLastPage_thenCorrect() {
final int pageSize = 10;
final Query queryTotal = entityManager.createQuery("Select count(f.id) from Foo f");
final long countResult = (long) queryTotal.getSingleResult();
final Query query = entityManager.createQuery("Select f from Foo as f order by f.id");
final int lastPage = (int) ((countResult / pageSize) + 1);
configurePagination(query, lastPage, pageSize);
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(lessThan(pageSize + 1)));
}
@SuppressWarnings("unchecked")
@Test
public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() {
final int pageSize = 10;
final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name");
final List<Integer> fooIds = queryIds.getResultList();
final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids");
query.setParameter("ids", fooIds.subList(0, pageSize));
final List<Foo> fooList = query.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenCorrect() {
final int pageSize = 10;
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult(0);
typedQuery.setMaxResults(pageSize);
final List<Foo> fooList = typedQuery.getResultList();
// Then
assertThat(fooList, hasSize(pageSize));
}
@Test
public final void givenEntitiesExist_whenRetrievingPageViaCriteria_thenNoExceptions() {
int pageNumber = 1;
final int pageSize = 10;
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
countQuery.select(criteriaBuilder.count(countQuery.from(Foo.class)));
final Long count = entityManager.createQuery(countQuery).getSingleResult();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
TypedQuery<Foo> typedQuery;
while (pageNumber < count.intValue()) {
typedQuery = entityManager.createQuery(select);
typedQuery.setFirstResult(pageNumber - 1);
typedQuery.setMaxResults(pageSize);
System.out.println("Current page: " + typedQuery.getResultList());
pageNumber += pageSize;
}
}
// UTIL
final int determineLastPage(final int pageSize, final long countResult) {
return (int) (countResult / pageSize) + 1;
}
final void configurePagination(final Query query, final int pageNumber, final int pageSize) {
query.setFirstResult((pageNumber - 1) * pageSize);
query.setMaxResults(pageSize);
}
}

View File

@ -0,0 +1,69 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class FooServicePersistenceIntegrationTest {
@Autowired
private FooService service;
// tests
@Test
public final void whenContextIsBootstrapped_thenNoExceptions() {
//
}
@Test
public final void whenEntityIsCreated_thenNoExceptions() {
service.create(new Foo(randomAlphabetic(6)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test(expected = DataIntegrityViolationException.class)
public final void whenEntityWithLongNameIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test(expected = InvalidDataAccessApiUsageException.class)
public final void whenSameEntityIsCreatedTwice_thenDataException() {
final Foo entity = new Foo(randomAlphabetic(8));
service.create(entity);
service.create(entity);
}
@Test(expected = DataAccessException.class)
public final void temp_whenInvalidEntityIsCreated_thenDataException() {
service.create(new Foo(randomAlphabetic(2048)));
}
@Test
public final void whenEntityIsCreated_thenFound() {
final Foo fooEntity = new Foo("abc");
service.create(fooEntity);
final Foo found = service.findOne(fooEntity.getId());
Assert.assertNotNull(found);
}
}

View File

@ -0,0 +1,118 @@
package org.baeldung.persistence.service;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Bar;
import org.baeldung.persistence.model.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
@SuppressWarnings("unchecked")
public class FooServiceSortingIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
// tests
@Test
public final void whenSortingByOneAttributeDefaultOrder_thenPrintSortedResult() {
final String jql = "Select f from Foo as f order by f.id";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingByOneAttributeSetOrder_thenSortedPrintResult() {
final String jql = "Select f from Foo as f order by f.id desc";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingByTwoAttributes_thenPrintSortedResult() {
final String jql = "Select f from Foo as f order by f.name asc, f.id desc";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
@Test
public final void whenSortingFooByBar_thenBarsSorted() {
final String jql = "Select f from Foo as f order by f.name, f.bar.id";
final Query barJoinQuery = entityManager.createQuery(jql);
final List<Foo> fooList = barJoinQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
if (foo.getBar() != null) {
System.out.print("-------BarId:" + foo.getBar().getId());
}
}
}
@Test
public final void whenSortinfBar_thenPrintBarsSortedWithFoos() {
final String jql = "Select b from Bar as b order by b.id";
final Query barQuery = entityManager.createQuery(jql);
final List<Bar> barList = barQuery.getResultList();
for (final Bar bar : barList) {
System.out.println("Bar Id:" + bar.getId());
for (final Foo foo : bar.getFooList()) {
System.out.println("FooName:" + foo.getName());
}
}
}
@Test
public final void whenSortingFooWithCriteria_thenPrintSortedFoos() {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
final List<Foo> fooList = typedQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId());
}
}
@Test
public final void whenSortingFooWithCriteriaAndMultipleAttributes_thenPrintSortedFoos() {
final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
final Root<Foo> from = criteriaQuery.from(Foo.class);
final CriteriaQuery<Foo> select = criteriaQuery.select(from);
criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")), criteriaBuilder.desc(from.get("id")));
final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
final List<Foo> fooList = typedQuery.getResultList();
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName() + "-------Id:" + foo.getId());
}
}
}

View File

@ -0,0 +1,64 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertNull;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.baeldung.config.PersistenceJPAConfig;
import org.baeldung.persistence.model.Foo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class)
@DirtiesContext
public class FooServiceSortingWitNullsManualIntegrationTest {
@PersistenceContext
private EntityManager entityManager;
@Autowired
private FooService service;
// tests
@SuppressWarnings("unchecked")
@Test
public final void whenSortingByStringNullLast_thenLastNull() {
service.create(new Foo());
service.create(new Foo(randomAlphabetic(6)));
final String jql = "Select f from Foo as f order by f.name desc NULLS LAST";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
assertNull(fooList.get(fooList.toArray().length - 1).getName());
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
}
}
@SuppressWarnings("unchecked")
@Test
public final void whenSortingByStringNullFirst_thenFirstNull() {
service.create(new Foo());
final String jql = "Select f from Foo as f order by f.name desc NULLS FIRST";
final Query sortQuery = entityManager.createQuery(jql);
final List<Foo> fooList = sortQuery.getResultList();
assertNull(fooList.get(0).getName());
for (final Foo foo : fooList) {
System.out.println("Name:" + foo.getName());
}
}
}

View File

@ -0,0 +1,123 @@
package org.baeldung.persistence.service;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.baeldung.config.PersistenceConfig;
import org.baeldung.persistence.model.Foo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
public class FooStoredProceduresLiveTest {
private static final Logger LOGGER = LoggerFactory.getLogger(FooStoredProceduresLiveTest.class);
@Autowired
private SessionFactory sessionFactory;
@Autowired
private FooService fooService;
private Session session;
@Before
public final void before() {
session = sessionFactory.openSession();
Assume.assumeTrue(getAllFoosExists());
Assume.assumeTrue(getFoosByNameExists());
}
private boolean getFoosByNameExists() {
try {
@SuppressWarnings("unchecked")
NativeQuery<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetFoosByName() Procedure is may be missing ", e);
return false;
}
}
private boolean getAllFoosExists() {
try {
@SuppressWarnings("unchecked")
NativeQuery<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
sqlQuery.list();
return true;
} catch (SQLGrammarException e) {
LOGGER.error("WARNING : GetAllFoos() Procedure is may be missing ", e);
return false;
}
}
@After
public final void after() {
session.close();
}
@Test
public final void getAllFoosUsingStoredProcedures() {
fooService.create(new Foo(randomAlphabetic(6)));
// Stored procedure getAllFoos using createSQLQuery
@SuppressWarnings("unchecked")
NativeQuery<Foo> sqlQuery = session.createSQLQuery("CALL GetAllFoos()").addEntity(Foo.class);
List<Foo> allFoos = sqlQuery.list();
for (Foo foo : allFoos) {
LOGGER.info("getAllFoos() SQL Query result : {}", foo.getName());
}
assertEquals(allFoos.size(), fooService.findAll().size());
// Stored procedure getAllFoos using a Named Query
@SuppressWarnings("unchecked")
Query<Foo> namedQuery = session.getNamedQuery("callGetAllFoos");
List<Foo> allFoos2 = namedQuery.list();
for (Foo foo : allFoos2) {
LOGGER.info("getAllFoos() NamedQuery result : {}", foo.getName());
}
assertEquals(allFoos2.size(), fooService.findAll().size());
}
@Test
public final void getFoosByNameUsingStoredProcedures() {
fooService.create(new Foo("NewFooName"));
// Stored procedure getFoosByName using createSQLQuery()
@SuppressWarnings("unchecked")
Query<Foo> sqlQuery = session.createSQLQuery("CALL GetFoosByName(:fooName)").addEntity(Foo.class).setParameter("fooName", "NewFooName");
List<Foo> allFoosByName = sqlQuery.list();
for (Foo foo : allFoosByName) {
LOGGER.info("getFoosByName() using SQL Query : found => {}", foo.toString());
}
// Stored procedure getFoosByName using getNamedQuery()
@SuppressWarnings("unchecked")
Query<Foo> namedQuery = session.getNamedQuery("callGetFoosByName").setParameter("fooName", "NewFooName");
List<Foo> allFoosByName2 = namedQuery.list();
for (Foo foo : allFoosByName2) {
LOGGER.info("getFoosByName() using Native Query : found => {}", foo.toString());
}
}
}

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

@ -608,6 +608,7 @@
<module>spring-5-reactive-security</module>
<module>spring-5-security</module>
<module>spring-5-security-oauth</module>
<module>spring-5-security-cognito</module>
<module>spring-activiti</module>
<module>spring-akka</module>
@ -634,7 +635,6 @@
<module>spring-boot-custom-starter</module>
<module>spring-boot-disable-console-logging</module>
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
<module>spring-boot-exceptions</module>
<module>spring-boot-jasypt</module>
<module>spring-boot-keycloak</module>
<module>spring-boot-logging-log4j2</module>
@ -819,6 +819,7 @@
<module>spring-5-reactive-security</module>
<module>spring-5-security</module>
<module>spring-5-security-oauth</module>
<module>spring-5-security-cognito</module>
<module>spring-activiti</module>
<module>spring-akka</module>
<module>spring-all</module>
@ -832,7 +833,6 @@
<module>spring-boot-camel</module>
<module>spring-boot-client</module>
<module>spring-boot-custom-starter</module>
<module>spring-boot-exceptions</module>
<module>greeter-spring-boot-autoconfigure</module>
<module>greeter-spring-boot-sample-app</module>
<module>persistence-modules/spring-boot-h2/spring-boot-h2-database</module>
@ -1271,7 +1271,7 @@
<module>spring-5-reactive-security</module>
<module>spring-5-security</module>
<module>spring-5-security-oauth</module>
<module>spring-5-security-cognito</module>
<module>spring-activiti</module>
<module>spring-akka</module>
<module>spring-all</module>
@ -1295,7 +1295,6 @@
<module>spring-boot-ctx-fluent</module>
<module>spring-boot-custom-starter</module>
<module>spring-boot-disable-console-logging</module>
<module>spring-boot-exceptions</module>
<!-- <module>spring-boot-gradle</module> --> <!-- Not a maven project -->
<module>spring-boot-jasypt</module>
<module>spring-boot-keycloak</module>

View File

@ -10,6 +10,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<dependencies>
@ -23,4 +24,4 @@
<properties>
<easy-rules.version>3.0.0</easy-rules.version>
</properties>
</project>
</project>

View File

@ -10,6 +10,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<dependencies>
@ -29,4 +30,4 @@
<openl.version>5.19.4</openl.version>
</properties>
</project>
</project>

View File

@ -10,6 +10,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<dependencies>
@ -24,4 +25,4 @@
<rulebook.version>0.6.2</rulebook.version>
</properties>
</project>
</project>

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