Merge branch 'master' into BAEL-6334-check-list-element-in-other-list

This commit is contained in:
Sam Gardner 2023-05-18 10:31:57 +01:00
commit 8430235bb1
279 changed files with 3732 additions and 1405 deletions

View File

@ -0,0 +1,138 @@
package com.baeldung.kafka;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Testcontainers
public class KafaConsumeLastNMessages {
private static String TOPIC1 = "baeldung-github";
private static String TOPIC2 = "baeldung-blog";
private static String MESSAGE_KEY = "message";
private static KafkaProducer<String, String> producer;
private static KafkaConsumer<String, String> consumer;
private static KafkaProducer<String, String> transactionalProducer;
@Container
private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
@BeforeAll
static void setup() {
KAFKA_CONTAINER.addExposedPort(9092);
Properties producerProperties = new Properties();
producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
Properties consumerProperties = new Properties();
consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
Properties transactionalProducerProprieties = new Properties();
transactionalProducerProprieties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
transactionalProducerProprieties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
transactionalProducerProprieties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
transactionalProducerProprieties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");
transactionalProducerProprieties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "prod-0");
producer = new KafkaProducer<>(producerProperties);
consumer = new KafkaConsumer<>(consumerProperties);
transactionalProducer = new KafkaProducer<>(transactionalProducerProprieties);
}
@AfterAll
static void destroy() {
KAFKA_CONTAINER.stop();
}
@Test
void whenSeekingKafkaTopicCursorToEnd_consumerRetrievesOnlyDesiredNumberOfMessages() throws ExecutionException, InterruptedException {
int messagesInTopic = 100;
int messagesToRetrieve = 20;
for (int i = 0; i < messagesInTopic; i++) {
producer.send(new ProducerRecord<>(TOPIC1, null, MESSAGE_KEY, String.valueOf(i)))
.get();
}
TopicPartition partition = new TopicPartition(TOPIC1, 0);
List<TopicPartition> partitions = new ArrayList<>();
partitions.add(partition);
consumer.assign(partitions);
consumer.seekToEnd(partitions);
long startIndex = consumer.position(partition) - messagesToRetrieve;
consumer.seek(partition, startIndex);
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
int recordsReceived = 0;
for (ConsumerRecord<String, String> record : records) {
assertEquals(MESSAGE_KEY, record.key());
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
recordsReceived++;
}
assertEquals(messagesToRetrieve, recordsReceived);
}
@Test
void havingTransactionalProducer_whenSeekingKafkaTopicCursorToEnd_consumerRetrievesLessMessages() throws ExecutionException, InterruptedException {
int messagesInTopic = 100;
int messagesToRetrieve = 20;
transactionalProducer.initTransactions();
for (int i = 0; i < messagesInTopic; i++) {
transactionalProducer.beginTransaction();
transactionalProducer.send(new ProducerRecord<>(TOPIC2, null, MESSAGE_KEY, String.valueOf(i)))
.get();
transactionalProducer.commitTransaction();
}
TopicPartition partition = new TopicPartition(TOPIC2, 0);
List<TopicPartition> partitions = new ArrayList<>();
partitions.add(partition);
consumer.assign(partitions);
consumer.seekToEnd(partitions);
long startIndex = consumer.position(partition) - messagesToRetrieve;
consumer.seek(partition, startIndex);
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMinutes(1));
int recordsReceived = 0;
for (ConsumerRecord<String, String> record : records) {
assertEquals(MESSAGE_KEY, record.key());
assertTrue(Integer.parseInt(record.value()) >= (messagesInTopic - messagesToRetrieve));
recordsReceived++;
}
assertTrue(messagesToRetrieve > recordsReceived);
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.s3;
import org.apache.http.HttpStatus;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
public class AWSS3ObjectUtils {
private AmazonS3 s3Client;
public AWSS3ObjectUtils(AmazonS3 s3client) {
this.s3Client = s3client;
}
public boolean doesObjectExistByDefaultMethod(String bucket, String key) {
return s3Client.doesObjectExist(bucket, key);
}
public boolean doesObjectExistByListObjects(String bucket, String key) {
return s3Client.listObjects(bucket)
.getObjectSummaries()
.stream()
.filter(s3ObjectSummary -> s3ObjectSummary.getKey()
.equals(key))
.findFirst()
.isPresent();
}
public boolean doesObjectExistByMetaData(String bucket, String key) {
try {
s3Client.getObjectMetadata(bucket, key);
return true;
} catch (AmazonServiceException e) {
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
return false;
} else {
throw e;
}
}
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.s3;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.auth.EnvironmentVariableCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
/**
* Required defined environment variables AWS_ACCESS_KEY_ID & AWS_ACCESS_KEY to access S3.
* Required S3 bucket and key that exist.
*/
public class AWSS3ObjectManualTest {
private static final String BUCKET = "your-bucket";
private static final String KEY_THAT_EXIST = "your-key-that-exist";
private AWSS3ObjectUtils s3ObjectUtils;
@Before
public void setUp() {
AmazonS3 client = AmazonS3ClientBuilder.standard()
.withRegion(Regions.DEFAULT_REGION)
.withCredentials(new EnvironmentVariableCredentialsProvider())
.build();
s3ObjectUtils = new AWSS3ObjectUtils(client);
}
@Test
public void whenVerifyIfObjectExistByDefaultMethod_thenCorrect() {
assertTrue(s3ObjectUtils.doesObjectExistByDefaultMethod(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
}
@Test
public void whenVerifyIfObjectExistByListObjects_thenCorrect() {
assertTrue(s3ObjectUtils.doesObjectExistByListObjects(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
}
@Test
public void whenVerifyIfObjectExistByMetaData_thenCorrect() {
assertTrue(s3ObjectUtils.doesObjectExistByMetaData(BUCKET, KEY_THAT_EXIST), "Key: " + KEY_THAT_EXIST + " doesn't exist");
}
}

View File

@ -1,10 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-5</artifactId>
<name>core-java-collections-5</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
<parent>

View File

@ -0,0 +1,39 @@
package com.baeldung.customiterators;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class CustomMovieIterator implements Iterator<Movie> {
private int currentIndex;
private final List<Movie> list;
public CustomMovieIterator(List<Movie> list) {
this.list = list;
this.currentIndex = 0;
}
@Override
public boolean hasNext() {
while (currentIndex < list.size()) {
Movie currentMovie = list.get(currentIndex);
if (isMovieEligible(currentMovie)) {
return true;
}
currentIndex++;
}
return false;
}
@Override
public Movie next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return list.get(currentIndex++);
}
private boolean isMovieEligible(Movie movie) {
return movie.getRating() >= 8;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.customiterators;
public class Movie {
private String name;
private String director;
private float rating;
public Movie(String name, String director, float rating) {
this.name = name;
this.director = director;
this.rating = rating;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
}

View File

@ -0,0 +1,139 @@
package com.baeldung.customiterators;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Please note that this class has been added for representation purposes of how a custom collection and its iterator would be.
* This does not have working code.
*/
public class MyList<E> implements List<E> {
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public boolean add(E e) {
return false;
}
@Override
public boolean remove(Object o) {
return false;
}
@Override
public Iterator<E> iterator() {
return new MyListIterator();
}
private class MyListIterator implements Iterator<E> {
@Override
public boolean hasNext() {
return false;
}
@Override
public E next() {
return null;
}
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <T> T[] toArray(T[] a) {
return null;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public boolean addAll(Collection<? extends E> c) {
return false;
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public void clear() {
}
@Override
public E get(int index) {
return null;
}
@Override
public E set(int index, E element) {
return null;
}
@Override
public void add(int index, E element) {
}
@Override
public E remove(int index) {
return null;
}
@Override
public int indexOf(Object o) {
return 0;
}
@Override
public int lastIndexOf(Object o) {
return 0;
}
@Override
public ListIterator<E> listIterator() {
return null;
}
@Override
public ListIterator<E> listIterator(int index) {
return null;
}
@Override
public List<E> subList(int fromIndex, int toIndex) {
return null;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.customiterators;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class PalindromIterator implements Iterator<String> {
private final List<String> list;
private int currentIndex;
public PalindromIterator(List<String> list) {
this.list = list;
this.currentIndex = 0;
}
@Override
public boolean hasNext() {
while (currentIndex < list.size()) {
String currString = list.get(currentIndex);
if (isPalindrome(currString)) {
return true;
}
currentIndex++;
}
return false;
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return list.get(currentIndex++);
}
private boolean isPalindrome(String input) {
for (int i = 0; i < input.length() / 2; i++) {
if (input.charAt(i) != input.charAt(input.length() - i - 1)) {
return false;
}
}
return true;
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.customiterators;
import static org.junit.Assert.assertEquals;
import java.util.Iterator;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class IteratorsUnitTest {
@Test
public void givenListOfStrings_whenIteratedWithDefaultIterator() {
List<String> listOfStrings = List.of("hello", "world", "this", "is", "a", "test");
Iterator<String> iterator = listOfStrings.iterator();
Assert.assertTrue(iterator.hasNext());
assertEquals(iterator.next(), "hello");
}
@Test
public void givenListOfStrings_whenPalindromIterator_thenOnlyPalindromes() {
List<String> listOfStrings = List.of("oslo", "madam", "car", "deed", "wow", "test");
PalindromIterator palindromIterator = new PalindromIterator(listOfStrings);
int count = 0;
while (palindromIterator.hasNext()) {
palindromIterator.next();
count++;
}
assertEquals(count, 3);
}
@Test
public void givenMovieList_whenMovieIteratorUsed_thenOnlyHighRatedMovies() {
List<Movie> movies = getMovies();
CustomMovieIterator movieIterator = new CustomMovieIterator(movies);
int count = 0;
while (movieIterator.hasNext()) {
movieIterator.next();
count++;
}
assertEquals(4, movies.size());
assertEquals(2, count);
}
private List<Movie> getMovies() {
Movie movie1 = new Movie("The Dark Knight", "Nolan", 10);
Movie movie2 = new Movie("Avatar", "Cameron", 9);
Movie movie3 = new Movie("Tenet", "Nolan", 7);
Movie movie4 = new Movie("Extraction", "Hargrave", 5);
return List.of(movie1, movie2, movie3, movie4);
}
}

View File

@ -14,6 +14,11 @@
</parent>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.36</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
@ -40,8 +45,8 @@
</dependencies>
<properties>
<jmh.version>1.21</jmh.version>
<commons-lang.version>2.2</commons-lang.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties>
</project>

View File

@ -0,0 +1,65 @@
package com.baeldung.arrayandlistperformance;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class ArrayAndArrayListPerformance {
@Benchmark
public void arrayCreation() {
int[] array = new int[1000000];
}
@Benchmark
public void arrayListCreation() {
ArrayList<Integer> list = new ArrayList<>(1000000);
}
@Benchmark
public void arrayItemSetting() {
int[] array = new int[1000000];
array[0] = 10;
}
@Benchmark
public void arrayListItemSetting() {
ArrayList<Integer> list = new ArrayList<>(1000000);
list.add(0, 10);
}
@Benchmark
public void arrayItemRetrieval() {
int[] array = new int[1000000];
array[0] = 10;
int item = array[0];
}
@Benchmark
public void arrayListItemRetrieval() {
ArrayList<Integer> list = new ArrayList<>(1000000);
list.add(0, 10);
int item2 = list.get(0);
}
@Benchmark
public void arrayCloning() {
int[] array = new int[1000000];
int[] newArray = array.clone();
}
@Benchmark
public void arrayListCloning() {
ArrayList<Integer> list = new ArrayList<>(1000000);
ArrayList<Integer> newList = new ArrayList<>(list);
}
public static void main(String[] args) throws Exception {
org.openjdk.jmh.runner.Runner runner = new org.openjdk.jmh.runner.Runner(new OptionsBuilder()
.include(ArrayAndArrayListPerformance.class.getSimpleName())
.forks(1)
.build());
runner.run();
}
}

View File

@ -4,4 +4,5 @@
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Java Concurrent HashSet Equivalent to ConcurrentHashMap](https://www.baeldung.com/java-concurrent-hashset-concurrenthashmap)
- [Reading and Writing With a ConcurrentHashMap](https://www.baeldung.com/concurrenthashmap-reading-and-writing)
- [ArrayBlockingQueue vs. LinkedBlockingQueue](https://www.baeldung.com/java-arrayblockingqueue-vs-linkedblockingqueue)
- [[<-- Prev]](/core-java-modules/core-java-concurrency-collections)

View File

@ -0,0 +1,26 @@
package com.baeldung.concurrent.queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BlockingQueueUnitTest {
@Test
public void givenArrayBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
BlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue<>(10);
arrayBlockingQueue.add("TestString1");
arrayBlockingQueue.add("TestString2");
assertEquals(8, arrayBlockingQueue.remainingCapacity());
}
@Test
public void givenLinkedBlockingQueue_whenAddedElements_thenReturnQueueRemainingCapacity() {
BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<>(10);
linkedBlockingQueue.add("TestString1");
assertEquals(9, linkedBlockingQueue.remainingCapacity());
}
}

View File

@ -8,3 +8,5 @@ This module contains articles about core Java input/output(IO) APIs.
- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
- [Java: Read Multiple Inputs on Same Line](https://www.baeldung.com/java-read-multiple-inputs-same-line)
- [Storing Java Scanner Input in an Array](https://www.baeldung.com/java-store-scanner-input-in-array)

View File

@ -10,4 +10,6 @@ This module contains articles about core Java input/output(IO) conversions.
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
- [How to Convert InputStream to Base64 String](https://www.baeldung.com/java-inputstream-to-base64-string)
- [Convert an OutputStream to an InputStream](https://www.baeldung.com/java-convert-outputstream-to-inputstream)
- [Java PrintStream to String](https://www.baeldung.com/java-printstream-to-string)
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)

View File

@ -0,0 +1,68 @@
package com.baeldung.printstreamtostring;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class PrintStreamToStringUtil {
public static String usingByteArrayOutputStreamClass(String input) throws IOException {
if (input == null) {
return null;
}
String output;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
output = outputStream.toString();
}
return output;
}
public static String usingApacheCommonsIO(String input) {
if (input == null) {
return null;
}
org.apache.commons.io.output.ByteArrayOutputStream outputStream = new org.apache.commons.io.output.ByteArrayOutputStream();
try (PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
}
return new String(outputStream.toByteArray());
}
public static String usingCustomOutputStream(String input) throws IOException {
if (input == null) {
return null;
}
String output;
try (CustomOutputStream outputStream = new CustomOutputStream(); PrintStream printStream = new PrintStream(outputStream)) {
printStream.print(input);
output = outputStream.toString();
}
return output;
}
private static class CustomOutputStream extends OutputStream {
private StringBuilder stringBuilder = new StringBuilder();
@Override
public void write(int b) throws IOException {
this.stringBuilder.append((char) b);
}
@Override
public String toString() {
return this.stringBuilder.toString();
}
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.outputstreamtoinputstream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import org.junit.jupiter.api.Test;
public class ConvertOutputStreamToInputStreamUnitTest {
@Test
void whenUsingByteArray_thenGetExpectedInputStream() throws IOException {
String content = "I'm an important message.";
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
out.write(content.getBytes());
try (ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray())) {
String inContent = new String(in.readAllBytes());
assertEquals(content, inContent);
}
}
}
@Test
void whenUsingPipeStream_thenGetExpectedInputStream() throws IOException {
String content = "I'm going through the pipe.";
ByteArrayOutputStream originOut = new ByteArrayOutputStream();
originOut.write(content.getBytes());
//connect the pipe
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
try (in) {
new Thread(() -> {
try (out) {
originOut.writeTo(out);
} catch (IOException iox) {
// handle IOExceptions
}
}).start();
String inContent = new String(in.readAllBytes());
assertEquals(content, inContent);
}
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.printstreamtostring;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
public class PrintStreamToStringUtilUnitTest {
@Test
public void whenUsingByteArrayOutputStreamClass_thenConvert() throws IOException {
assertEquals("test", PrintStreamToStringUtil.usingByteArrayOutputStreamClass("test"));
assertEquals("", PrintStreamToStringUtil.usingByteArrayOutputStreamClass(""));
assertNull(PrintStreamToStringUtil.usingByteArrayOutputStreamClass(null));
}
@Test
public void whenCustomOutputStream_thenConvert() throws IOException {
assertEquals("world", PrintStreamToStringUtil.usingCustomOutputStream("world"));
assertEquals("", PrintStreamToStringUtil.usingCustomOutputStream(""));
assertNull(PrintStreamToStringUtil.usingCustomOutputStream(null));
}
@Test
public void whenUsingApacheCommonsIO_thenConvert() {
assertEquals("hello", PrintStreamToStringUtil.usingApacheCommonsIO("hello"));
assertEquals("", PrintStreamToStringUtil.usingApacheCommonsIO(""));
assertNull(PrintStreamToStringUtil.usingApacheCommonsIO(null));
}
}

View File

@ -23,7 +23,7 @@
</dependencies>
<properties>
<h2.version>1.4.197</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
<h2.version>2.1.214</h2.version>
</properties>
</project>

View File

@ -8,3 +8,4 @@ This module contains articles about Object-oriented programming (OOP) patterns i
- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object)
- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy)
- [Using an Interface vs. Abstract Class in Java](https://www.baeldung.com/java-interface-vs-abstract-class)
- [Should We Create an Interface for Only One Implementation?](https://www.baeldung.com/java-interface-single-implementation)

View File

@ -0,0 +1,5 @@
package com.baeldung.interfacesingleimpl;
public interface Animal {
String makeSound();
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfacesingleimpl;
public class AnimalCare {
private Animal animal;
public AnimalCare(Animal animal) {
this.animal = animal;
}
public String animalSound() {
return animal.makeSound();
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.interfacesingleimpl;
public class Cat {
private String name;
public Cat(String name) {
this.name = name;
}
public String makeSound() {
return "Meow! My name is " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.interfacesingleimpl;
public class Dog implements Animal {
private String name;
public Dog(String name) {
this.name = name;
}
@Override
public String makeSound() {
return "Woof! My name is " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.interfacesingleimpl;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class InterfaceSingleImplUnitTest {
@Test
public void whenUsingMockAnimal_thenAnimalSoundIsCorrect() {
MockAnimal mockAnimal = new MockAnimal();
String expected = "Mock animal sound!";
AnimalCare animalCare = new AnimalCare(mockAnimal);
assertThat(animalCare.animalSound()).isEqualTo(expected);
}
@Test
public void whenCreatingDog_thenDogMakesWoofSound() {
Dog dog = new Dog("Buddy");
String expected = "Woof! My name is Buddy";
assertThat(dog.makeSound()).isEqualTo(expected);
}
@Test
public void whenCreatingCat_thenCatMakesMeowSound() {
Cat cat = new Cat("FuzzBall");
String expected = "Meow! My name is FuzzBall";
assertThat(cat.makeSound()).isEqualTo(expected);
}
@Test
public void whenCreatingAnimalCareWithDog_thenDogMakesWoofSound() {
Animal dog = new Dog("Ham");
AnimalCare animalCare = new AnimalCare(dog);
String expected = "Woof! My name is Ham";
assertThat(animalCare.animalSound()).isEqualTo(expected);
}
@Test
public void whenCreatingCatCareWithCat_thenCatMakesMeowSound() {
Cat cat = new Cat("Grumpy");
String expected = "Meow! My name is Grumpy";
assertThat(cat.makeSound()).isEqualTo(expected);
}
@Test
public void whenCreatingMockAnimal_thenMockAnimalMakesMockAnimalSound() {
MockAnimal mockAnimal = new MockAnimal();
String expected = "Mock animal sound!";
assertThat(mockAnimal.makeSound()).isEqualTo(expected);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.interfacesingleimpl;
public class MockAnimal implements Animal {
@Override
public String makeSound() {
return "Mock animal sound!";
}
}

View File

@ -6,4 +6,5 @@
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches)
- [Getting the Text That Follows After the Regex Match in Java](https://www.baeldung.com/java-regex-text-after-match)
- [Regular Expression: \z vs \Z Anchors in Java](https://www.baeldung.com/java-regular-expression-z-vs-z-anchors)
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)

View File

@ -30,12 +30,18 @@
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>${spring-security-crypto.version}</version>
</dependency>
</dependencies>
<properties>
<bouncycastle.version>1.60</bouncycastle.version>
<bouncycastle.version>1.70</bouncycastle.version>
<commons-codec.version>1.11</commons-codec.version>
<jaxb-api.version>2.3.1</jaxb-api.version>
<spring-security-crypto.version>6.0.3</spring-security-crypto.version>
</properties>
</project>

View File

@ -0,0 +1,65 @@
package com.baeldung.hash.argon;
import static org.junit.jupiter.api.Assertions.*;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters;
import org.bouncycastle.util.encoders.Hex;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import java.util.Arrays;
import java.util.Base64;
public class HashPasswordUnitTest {
@Test
public void givenRawPassword_whenEncodedWithArgon2_thenMatchesEncodedPassword() {
String rawPassword = "Baeldung";
Argon2PasswordEncoder arg2SpringSecurity = new Argon2PasswordEncoder(16, 32, 1, 60000, 10);
String hashPassword = arg2SpringSecurity.encode(rawPassword);
assertTrue(arg2SpringSecurity.matches(rawPassword, hashPassword));
}
@Test
public void givenRawPasswordAndSalt_whenArgon2AlgorithmIsUsed_thenHashIsCorrect() {
byte[] salt = generateSalt16Byte();
String password = "Baeldung";
int iterations = 2;
int memLimit = 66536;
int hashLength = 32;
int parallelism = 1;
Argon2Parameters.Builder builder = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id).withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(iterations)
.withMemoryAsKB(memLimit)
.withParallelism(parallelism)
.withSalt(salt);
Argon2BytesGenerator generate = new Argon2BytesGenerator();
generate.init(builder.build());
byte[] result = new byte[hashLength];
generate.generateBytes(password.getBytes(StandardCharsets.UTF_8), result, 0, result.length);
Argon2BytesGenerator verifier = new Argon2BytesGenerator();
verifier.init(builder.build());
byte[] testHash = new byte[hashLength];
verifier.generateBytes(password.getBytes(StandardCharsets.UTF_8), testHash, 0, testHash.length);
assertTrue(Arrays.equals(result, testHash));
}
private static byte[] generateSalt16Byte() {
SecureRandom secureRandom = new SecureRandom();
byte[] salt = new byte[16];
secureRandom.nextBytes(salt);
return salt;
}
}

View File

@ -4,3 +4,4 @@ This module contains articles about string APIs.
### Relevant Articles:
- [Retain Only Digits and Decimal Separator in String](https://www.baeldung.com/java-string-retain-digits-decimal)
- [Difference Between null and Empty String in Java](https://www.baeldung.com/java-string-null-vs-empty)

View File

@ -97,7 +97,7 @@
<module>core-java-lang-oop-constructors</module>
<module>core-java-lang-oop-patterns</module>
<module>core-java-lang-oop-generics</module>
<!-- <module>core-java-lang-oop-modifiers</module>-->
<module>core-java-lang-oop-modifiers</module>
<module>core-java-lang-oop-types</module>
<module>core-java-lang-oop-types-2</module>
<module>core-java-lang-oop-inheritance</module>

View File

@ -0,0 +1,9 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf

View File

@ -0,0 +1,5 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build

View File

@ -0,0 +1,19 @@
plugins {
id 'java'
}
group = "com.baeldung.gradle"
version = "1.0.0-SNAPSHOT"
sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
implementation group: 'org.apache.commons', name: 'commons-collections4', version: '4.+'
implementation group: 'org.apache.commons', name: 'commons-math3', version: '[3.4, 3.5)'
implementation group: 'org.apache.commons', name: 'commons-text', version: 'latest.release'
}

View File

@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,10 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user manual at https://docs.gradle.org/8.0.2/userguide/multi_project_builds.html
*/
rootProject.name = 'dependency-version'

View File

@ -94,7 +94,7 @@
<rest-assured.version>3.3.0</rest-assured.version>
<!-- plugins -->
<thin.version>1.0.22.RELEASE</thin.version>
<spring-boot.version>2.7.8</spring-boot.version>
<spring-boot.version>2.7.11</spring-boot.version>
<aspectjweaver.version>1.9.1</aspectjweaver.version>
<mysql-connector-java.version>8.0.31</mysql-connector-java.version>
</properties>

View File

@ -76,13 +76,18 @@
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.hypersistence</groupId>
<artifactId>hypersistence-utils-hibernate-60</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
<properties>
<!-- Spring -->
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
<hibernate-core.version>5.6.7.Final</hibernate-core.version>
<org.springframework.version>6.0.6</org.springframework.version>
<org.springframework.data.version>3.0.3</org.springframework.data.version>
<hibernate-core.version>6.1.7.Final</hibernate-core.version>
<maven.deploy.skip>true</maven.deploy.skip>
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
</properties>

View File

@ -2,9 +2,9 @@ package com.baeldung.hibernate.creationupdatetimestamp.model;
import java.time.Instant;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

View File

@ -1,11 +1,11 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@ -14,74 +14,51 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class AddressType implements CompositeUserType {
public class AddressType implements CompositeUserType<Address>, UserType<Address> {
@Override
public String[] getPropertyNames() {
return new String[]{"addressLine1", "addressLine2",
"city", "country", "zipcode"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Address empAdd = (Address) component;
public Object getPropertyValue(Address component, int property) throws HibernateException {
switch (property) {
case 0:
return empAdd.getAddressLine1();
return component.getAddressLine1();
case 1:
return empAdd.getAddressLine2();
return component.getAddressLine2();
case 2:
return empAdd.getCity();
return component.getCity();
case 3:
return empAdd.getCountry();
return component.getCountry();
case 4:
return Integer.valueOf(empAdd.getZipCode());
}
return component.getZipCode();
default:
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Address empAdd = (Address) component;
switch (property) {
case 0:
empAdd.setAddressLine1((String) value);
case 1:
empAdd.setAddressLine2((String) value);
case 2:
empAdd.setCity((String) value);
case 3:
empAdd.setCountry((String) value);
case 4:
empAdd.setZipCode((Integer) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
return null;
}
@Override
public Class<?> embeddable() {
return Address.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public int getSqlType() {
return Types.VARCHAR;
}
@Override
public Class<Address> returnedClass() {
return Address.class;
}
@Override
public boolean equals(Address x, Address y) {
if (x == y)
return true;
@ -92,57 +69,52 @@ public class AddressType implements CompositeUserType {
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
public Address nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Address empAdd = new Address();
empAdd.setAddressLine1(rs.getString(names[0]));
empAdd.setAddressLine1(rs.getString(position));
if (rs.wasNull())
return null;
empAdd.setAddressLine2(rs.getString(names[1]));
empAdd.setCity(rs.getString(names[2]));
empAdd.setCountry(rs.getString(names[3]));
empAdd.setZipCode(rs.getInt(names[4]));
empAdd.setAddressLine2(rs.getString(position));
empAdd.setCity(rs.getString(position));
empAdd.setCountry(rs.getString(position));
empAdd.setZipCode(rs.getInt(position));
return empAdd;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, Address value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
Address empAdd = (Address) value;
st.setString(index, empAdd.getAddressLine1());
st.setString(index + 1, empAdd.getAddressLine2());
st.setString(index + 2, empAdd.getCity());
st.setString(index + 3, empAdd.getCountry());
st.setInt(index + 4, empAdd.getZipCode());
st.setString(index, value.getAddressLine1());
st.setString(index + 1, value.getAddressLine2());
st.setString(index + 2, value.getCity());
st.setString(index + 3, value.getCountry());
st.setInt(index + 4, value.getZipCode());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public Address deepCopy(Address value) {
if (Objects.isNull(value))
return null;
Address oldEmpAdd = (Address) value;
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
newEmpAdd.setCity(oldEmpAdd.getCity());
newEmpAdd.setCountry(oldEmpAdd.getCountry());
newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@ -153,17 +125,27 @@ public class AddressType implements CompositeUserType {
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object, SessionFactoryImplementor sessionFactory) {
return CompositeUserType.super.isInstance(object, sessionFactory);
}
@Override
public boolean isSameClass(Object object, SessionFactoryImplementor sessionFactory) {
return CompositeUserType.super.isSameClass(object, sessionFactory);
}
}

View File

@ -1,14 +1,14 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.type.LocalDateType;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalDate> {
import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor;
public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor<LocalDate> {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
@ -18,12 +18,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
@Override
public String toString(LocalDate value) {
return LocalDateType.FORMATTER.format(value);
return DateTimeFormatter.ISO_LOCAL_DATE.format(value);
}
@Override
public LocalDate fromString(String string) {
return LocalDate.from(LocalDateType.FORMATTER.parse(string));
public LocalDate fromString(CharSequence string) {
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string));
}
@Override
@ -33,7 +33,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
return null;
if (String.class.isAssignableFrom(type))
return (X) LocalDateType.FORMATTER.format(value);
return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value);
throw unknownUnwrap(type);
}
@ -44,7 +44,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD
return null;
if(String.class.isInstance(value))
return LocalDate.from(LocalDateType.FORMATTER.parse((CharSequence) value));
return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse((CharSequence) value));
throw unknownWrap(value.getClass());
}

View File

@ -2,18 +2,16 @@ package com.baeldung.hibernate.customtypes;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.AbstractSingleColumnStandardBasicType;
import org.hibernate.type.DiscriminatorType;
import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor;
import org.hibernate.type.descriptor.jdbc.VarcharJdbcType;
import java.time.LocalDate;
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> implements DiscriminatorType<LocalDate> {
public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<LocalDate> {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<L
return "LocalDateString";
}
@Override
public LocalDate stringToObject(String xml) throws Exception {
public LocalDate stringToObject(String xml) {
return fromString(xml);
}
@Override
public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception {
return '\'' + toString(value) + '\'';
public String objectToSQLString(LocalDate value, Dialect dialect) {
return '\'' + LocalDateStringJavaDescriptor.INSTANCE.toString(value) + '\'';
}
}

View File

@ -1,20 +1,19 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.CompositeType;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.usertype.UserTypeLegacyBridge;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.AttributeOverride;
import jakarta.persistence.AttributeOverrides;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.LocalDate;
@TypeDef(name = "PhoneNumber",
typeClass = PhoneNumberType.class,
defaultForType = PhoneNumber.class)
@Entity
@Table(name = "OfficeEmployee")
public class OfficeEmployee {
@ -24,25 +23,36 @@ public class OfficeEmployee {
private long id;
@Column
@Type(type = "LocalDateString")
@Type(
value = UserTypeLegacyBridge.class,
parameters = @Parameter(name = UserTypeLegacyBridge.TYPE_NAME_PARAM_KEY, value = "LocalDateString")
)
private LocalDate dateOfJoining;
@Columns(columns = {@Column(name = "country_code"),
@Column(name = "city_code"),
@Column(name = "number")})
@AttributeOverrides({
@AttributeOverride(name = "countryCode", column = @Column(name = "country_code")),
@AttributeOverride(name = "cityCode", column = @Column(name = "city_code")),
@AttributeOverride(name = "number", column = @Column(name = "number"))
})
@Type(value = PhoneNumberType.class)
private PhoneNumber employeeNumber;
@Columns(columns = {@Column(name = "address_line_1"),
@Column(name = "address_line_2"),
@Column(name = "city"), @Column(name = "country"),
@Column(name = "zip_code")})
@Type(type = "com.baeldung.hibernate.customtypes.AddressType")
@CompositeType(value = com.baeldung.hibernate.customtypes.AddressType.class)
@AttributeOverrides({
@AttributeOverride(name = "addressLine1", column = @Column(name = "address_line_1")),
@AttributeOverride(name = "addressLine2", column = @Column(name = "address_line_2")),
@AttributeOverride(name = "city", column = @Column(name = "city")),
@AttributeOverride(name = "country", column = @Column(name = "country")),
@AttributeOverride(name = "zipCode", column = @Column(name = "zip_code"))
})
private Address empAddress;
@Type(type = "com.baeldung.hibernate.customtypes.SalaryType",
@Type(value = com.baeldung.hibernate.customtypes.SalaryType.class,
parameters = {@Parameter(name = "currency", value = "USD")})
@Columns(columns = {@Column(name = "amount"),
@Column(name = "currency")})
@AttributeOverrides({
@AttributeOverride(name = "amount", column = @Column(name = "amount")),
@AttributeOverride(name = "currency", column = @Column(name = "currency"))
})
private Salary salary;
public Salary getSalary() {

View File

@ -2,11 +2,11 @@ package com.baeldung.hibernate.customtypes;
import java.util.Objects;
public final class PhoneNumber {
public class PhoneNumber {
private final int countryCode;
private final int cityCode;
private final int number;
private int countryCode;
private int cityCode;
private int number;
public PhoneNumber(int countryCode, int cityCode, int number) {
this.countryCode = countryCode;

View File

@ -1,6 +1,5 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
@ -11,11 +10,11 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
public class PhoneNumberType implements UserType<PhoneNumber> {
public class PhoneNumberType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
public int getSqlType() {
return Types.INTEGER;
}
@Override
@ -24,7 +23,7 @@ public class PhoneNumberType implements UserType {
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public boolean equals(PhoneNumber x, PhoneNumber y) {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
@ -34,48 +33,42 @@ public class PhoneNumberType implements UserType {
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(PhoneNumber x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
int countryCode = rs.getInt(names[0]);
public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
int countryCode = rs.getInt(position);
if (rs.wasNull())
return null;
int cityCode = rs.getInt(names[1]);
int number = rs.getInt(names[2]);
PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
int cityCode = rs.getInt(position);
int number = rs.getInt(position);
return employeeNumber;
return new PhoneNumber(countryCode, cityCode, number);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
st.setNull(index+1, Types.INTEGER);
st.setNull(index+2, Types.INTEGER);
} else {
PhoneNumber employeeNumber = (PhoneNumber) value;
st.setInt(index,employeeNumber.getCountryCode());
st.setInt(index+1,employeeNumber.getCityCode());
st.setInt(index+2,employeeNumber.getNumber());
st.setInt(index, value.getCountryCode());
st.setInt(index+1, value.getCityCode());
st.setInt(index+2, value.getNumber());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public PhoneNumber deepCopy(PhoneNumber value) {
if (Objects.isNull(value))
return null;
PhoneNumber empNumber = (PhoneNumber) value;
PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
return newEmpNumber;
return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber());
}
@Override
@ -84,17 +77,17 @@ public class PhoneNumberType implements UserType {
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
public Serializable disassemble(PhoneNumber value) {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
public PhoneNumber assemble(Serializable cached, Object owner) {
return (PhoneNumber) cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) {
return detached;
}
}

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@ -16,65 +16,47 @@ import java.sql.Types;
import java.util.Objects;
import java.util.Properties;
public class SalaryType implements CompositeUserType, DynamicParameterizedType {
public class SalaryType implements UserType<Salary>, CompositeUserType<Salary>, DynamicParameterizedType {
private String localCurrency;
@Override
public String[] getPropertyNames() {
return new String[]{"amount", "currency"};
}
@Override
public Type[] getPropertyTypes() {
return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
}
@Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
Salary salary = (Salary) component;
public Object getPropertyValue(Salary component, int property) throws HibernateException {
switch (property) {
case 0:
return salary.getAmount();
return component.getAmount();
case 1:
return salary.getCurrency();
}
return component.getCurrency();
default:
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
Salary salary = (Salary) component;
switch (property) {
case 0:
salary.setAmount((Long) value);
case 1:
salary.setCurrency((String) value);
}
throw new IllegalArgumentException(property +
" is an invalid property index for class type " +
component.getClass().getName());
}
@Override
public Class returnedClass() {
public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
return null;
}
@Override
public Class<?> embeddable() {
return Salary.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public int getSqlType() {
return Types.BIGINT;
}
@Override
public Class<Salary> returnedClass() {
return Salary.class;
}
@Override
public boolean equals(Salary x, Salary y) {
if (x == y)
return true;
@ -82,54 +64,48 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
return false;
return x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
public int hashCode(Salary x) {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Salary salary = new Salary();
salary.setAmount(rs.getLong(names[0]));
salary.setAmount(rs.getLong(position));
if (rs.wasNull())
return null;
salary.setCurrency(rs.getString(names[1]));
salary.setCurrency(rs.getString(position));
return salary;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.BIGINT);
else {
Salary salary = (Salary) value;
st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
salary.getCurrency(), localCurrency));
st.setString(index + 1, salary.getCurrency());
st.setLong(index, SalaryCurrencyConvertor.convert(
value.getAmount(),
value.getCurrency(), localCurrency));
st.setString(index + 1, value.getCurrency());
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
Salary oldSal = (Salary) value;
Salary newSal = new Salary();
newSal.setAmount(oldSal.getAmount());
newSal.setCurrency(oldSal.getCurrency());
newSal.setAmount(value.getAmount());
newSal.setCurrency(value.getCurrency());
return newSal;
}
@ -140,18 +116,18 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
public Serializable disassemble(Salary value) {
return (Serializable) deepCopy(value);
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return deepCopy(cached);
public Salary assemble(Serializable cached, Object owner) {
return deepCopy((Salary) cached);
}
@Override
public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
return original;
public Salary replace(Salary detached, Salary managed, Object owner) {
return detached;
}
@Override

View File

@ -4,7 +4,7 @@ import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import jakarta.persistence.*;
import java.util.Set;
@Entity

View File

@ -3,7 +3,7 @@ package com.baeldung.hibernate.immutable.entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Immutable;
import javax.persistence.*;
import jakarta.persistence.*;
@Entity
@Immutable

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
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 jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
@Entity
public class Email {

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.joincolumn;
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.JoinColumns;
import javax.persistence.ManyToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinColumns;
import jakarta.persistence.ManyToOne;
@Entity
public class Office {

View File

@ -1,10 +1,10 @@
package com.baeldung.hibernate.joincolumn;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class OfficeAddress {

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
import java.util.List;
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 jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
@Entity
public class OfficialEmployee {

View File

@ -3,12 +3,12 @@ package com.baeldung.hibernate.lazycollection.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.OneToMany;
import javax.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OrderColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Entity;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,11 +1,10 @@
package com.baeldung.hibernate.lazycollection.model;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OrderColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Entity;
@Entity
public class Employee {

View File

@ -43,8 +43,8 @@ public class HibernateAnnotationUtil {
return metadata.buildSessionFactory();
}
private static Map<String, String> dbSettings() {
Map<String, String> dbSettings = new HashMap<>();
private static Map<String, Object> dbSettings() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");

View File

@ -2,13 +2,13 @@ package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "CART")

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
@Entity
@Table(name = "CARTOIO")

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.oneToMany.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "ITEMS")

View File

@ -1,12 +1,12 @@
package com.baeldung.hibernate.oneToMany.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "ITEMSOIO")

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.io.Serializable;
@Entity

View File

@ -3,10 +3,10 @@ package com.baeldung.hibernate.wherejointable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
@Entity(name = "e_group")
public class Group {

View File

@ -3,12 +3,12 @@ package com.baeldung.hibernate.wherejointable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.JoinTable;
import jakarta.persistence.ManyToMany;
import org.hibernate.annotations.WhereJoinTable;

View File

@ -2,11 +2,11 @@ package com.baeldung.hibernate.wherejointable;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
@Entity(name = "r_user_group")
public class UserGroupRelation implements Serializable {

View File

@ -7,12 +7,12 @@
<description>Hibernate EntityManager Demo</description>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -1,5 +1,6 @@
package com.baeldung.hibernate.creationupdatetimestamp;
import static org.hibernate.FlushMode.MANUAL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@ -71,22 +72,22 @@ class HibernateCreationUpdateTimestampIntegrationTest {
}
@Test
void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreNotEqual() {
void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() {
session = sessionFactory.openSession();
session.beginTransaction();
Book book = new Book();
session.save(book);
session.getTransaction()
.commit();
session.getTransaction().commit();
session.close();
assertNotEquals(book.getCreatedOn(), book.getLastUpdatedOn());
assertEquals(book.getCreatedOn(), book.getLastUpdatedOn());
}
@Test
void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() {
session = sessionFactory.openSession();
session.setHibernateFlushMode(MANUAL);
session.beginTransaction();
Book book = new Book();
session.save(book);
@ -96,8 +97,9 @@ class HibernateCreationUpdateTimestampIntegrationTest {
String newName = "newName";
book.setTitle(newName);
session.getTransaction()
.commit();
session.save(book);
session.flush();
session.getTransaction().commit();
session.close();
Instant createdOnAfterUpdate = book.getCreatedOn();
Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn();

View File

@ -6,10 +6,9 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
import org.junit.Assert;
import org.junit.Test;
import javax.persistence.TypedQuery;
import jakarta.persistence.TypedQuery;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
@ -76,7 +75,7 @@ public class HibernateCustomTypesIntegrationTest {
doInHibernate(this::sessionFactory, session -> {
session.save(e);
TypedQuery<OfficeEmployee> query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class);
TypedQuery<OfficeEmployee> query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipCode = :pinCode", OfficeEmployee.class);
query.setParameter("pinCode",100);
int size = query.getResultList().size();
@ -100,8 +99,8 @@ public class HibernateCustomTypesIntegrationTest {
return metadata.buildSessionFactory();
}
private static Map<String, String> getProperties() {
Map<String, String> dbSettings = new HashMap<>();
private static Map<String, Object> getProperties() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");

View File

@ -8,7 +8,7 @@ import org.hibernate.Session;
import org.junit.*;
import org.junit.rules.ExpectedException;
import javax.persistence.PersistenceException;
import jakarta.persistence.PersistenceException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

View File

@ -78,8 +78,8 @@ public class JoinColumnIntegrationTest {
return metadata.buildSessionFactory();
}
private static Map<String, String> getProperties() {
Map<String, String> dbSettings = new HashMap<>();
private static Map<String, Object> getProperties() {
Map<String, Object> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");

View File

@ -78,10 +78,11 @@
</repositories>
<properties>
<hibernate.version>5.3.7.Final</hibernate.version>
<mysql.version>6.0.6</mysql.version>
<mariaDB4j.version>2.2.3</mariaDB4j.version>
<hibernate.version>6.1.7.Final</hibernate.version>
<mysql.version>8.0.32</mysql.version>
<mariaDB4j.version>2.6.0</mariaDB4j.version>
<geodb.version>0.9</geodb.version>
<byte-buddy.version>1.14.2</byte-buddy.version>
</properties>
</project>

View File

@ -1,6 +1,6 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
import jakarta.persistence.Entity;
@Entity
public class EntityWithNoId {

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "PRODUCT")

View File

@ -1,8 +1,8 @@
package com.baeldung.hibernate.exception;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "PRODUCT")

View File

@ -0,0 +1,32 @@
package com.baeldung.hibernate.exception;
public class ProductNotMapped {
private int id;
private String name;
private String description;
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;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.logging;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Employee {

View File

@ -1,11 +1,11 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Point;
import org.locationtech.jts.geom.Point;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class PointEntity {

View File

@ -1,10 +1,10 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Polygon;
import org.locationtech.jts.geom.Polygon;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class PolygonEntity {

View File

@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Student {

View File

@ -1,8 +1,8 @@
package com.baeldung.persistence.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
@Entity
public class Person {

View File

@ -7,12 +7,12 @@
<description>Hibernate EntityManager Demo</description>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="jakarta.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jakarta.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/>
<property name="jakarta.persistence.jdbc.user" value="root"/>
<property name="jakarta.persistence.jdbc.password" value="root"/>
</properties>
</persistence-unit>
</persistence>

View File

@ -9,23 +9,23 @@ import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import javax.persistence.Query;
import jakarta.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.util.GeometricShapeFactory;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.util.GeometricShapeFactory;
import geodb.GeoDB;
@ -39,7 +39,7 @@ public class HibernateSpatialIntegrationTest {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
session.doWork(GeoDB::InitGeoDB);
}
@After
@ -135,9 +135,7 @@ public class HibernateSpatialIntegrationTest {
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
Geometry geom = null;
geom = fromText.read(wellKnownText);
return geom;
return fromText.read(wellKnownText);
}
private static Geometry createCircle(double x, double y, double radius) {

View File

@ -6,28 +6,25 @@ import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.List;
import javax.persistence.OptimisticLockException;
import javax.persistence.PersistenceException;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PersistenceException;
import org.hibernate.AnnotationException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PropertyValueException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.hql.internal.ast.QuerySyntaxException;
import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.sqm.UnknownEntityException;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.junit.Before;
@ -63,12 +60,15 @@ public class HibernateExceptionUnitTest {
@Test
public void whenQueryExecutedWithUnmappedEntity_thenMappingException() {
thrown.expectCause(isA(MappingException.class));
thrown.expectMessage("Unknown entity: java.lang.String");
thrown.expect(isA(MappingException.class));
thrown.expectMessage("Unable to locate persister: com.baeldung.hibernate.exception.ProductNotMapped");
ProductNotMapped product = new ProductNotMapped();
product.setId(1);
product.setName("test");
Session session = sessionFactory.openSession();
NativeQuery<String> query = session.createNativeQuery("select name from PRODUCT", String.class);
query.getResultList();
session.save(product);
}
@Test
@ -82,8 +82,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() {
thrown.expectCause(isA(QuerySyntaxException.class));
thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]");
thrown.expectCause(isA(UnknownEntityException.class));
thrown.expectMessage("Could not resolve root entity 'PRODUCT");
Session session = sessionFactory.openSession();
List<Product> results = session.createQuery("from PRODUCT", Product.class)
@ -92,8 +92,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
thrown.expect(AnnotationException.class);
thrown.expectMessage("No identifier specified for entity");
thrown.expect(isA(HibernateException.class));
thrown.expectMessage("Entity 'com.baeldung.hibernate.exception.EntityWithNoId' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(EntityWithNoId.class);
@ -132,9 +132,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown.expectMessage("SQLGrammarException: could not prepare statement");
thrown.expectMessage("could not prepare statement");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(Product.class);
@ -162,9 +161,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
thrown.expectMessage("SQLGrammarException: could not prepare statement");
thrown.expectMessage("could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class);
@ -173,9 +171,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenDuplicateIdSaved_thenConstraintViolationException() {
thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(ConstraintViolationException.class));
thrown.expectMessage("ConstraintViolationException: could not execute statement");
thrown.expectMessage("could not execute statement");
Session session = null;
Transaction transaction = null;
@ -253,7 +250,7 @@ public class HibernateExceptionUnitTest {
@Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class));
thrown.expectMessage("org.hibernate.exception.DataException: could not prepare statement");
thrown.expectMessage("could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery<Product> query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class);
@ -330,9 +327,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenUpdatingNonExistingObject_thenStaleStateException() {
thrown.expect(isA(OptimisticLockException.class));
thrown.expectMessage("Row was updated or deleted by another transaction");
thrown.expectCause(isA(StaleObjectStateException.class));
thrown.expectCause(isA(StaleStateException.class));
thrown.expectMessage("Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update PRODUCT set description=?, name=? where id=?");
Session session = null;
Transaction transaction = null;
@ -356,7 +352,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() {
thrown.expect(isA(TransactionException.class));
thrown.expect(isA(IllegalStateException.class));
thrown.expectMessage("Transaction already active");
Session session = null;
Transaction transaction = null;
@ -368,6 +365,7 @@ public class HibernateExceptionUnitTest {
product1.setId(15);
product1.setName("Product1");
session.save(product1);
transaction = session.beginTransaction();
transaction.setRollbackOnly();
transaction.commit();

View File

@ -2,9 +2,9 @@ package com.baeldung.hibernate.multitenancy;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity(name = "Car")
@Table(name = "Car")

View File

@ -79,9 +79,9 @@ public abstract class MultitenancyIntegrationTest {
private void createCarTable() {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.createSQLQuery("drop table Car if exists")
session.createNativeQuery("drop table Car if exists")
.executeUpdate();
session.createSQLQuery("create table Car (brand varchar(255) primary key)")
session.createNativeQuery("create table Car (brand varchar(255) primary key)")
.executeUpdate();
tx.commit();
}

View File

@ -1,7 +1,5 @@
package com.baeldung.hibernate.multitenancy.database;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest;
@ -14,7 +12,7 @@ public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyInt
}
@Test
public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException {
public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() {
whenCurrentTenantIs(TenantIdNames.MYDB1);
whenAddCar("myCar");
thenCarFound("myCar");

View File

@ -34,8 +34,13 @@ public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnect
private void initConnectionProviderForTenant(String tenantId) throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId)));
Map<String, Object> configProperties = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
configProperties.put(key, value);
}
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
connectionProvider.configure(configProperties);
this.connectionProviderMap.put(tenantId, connectionProvider);
}

View File

@ -3,6 +3,8 @@ package com.baeldung.hibernate.multitenancy.schema;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
@ -39,9 +41,14 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn
private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
Map<String, Object> configProperties = new HashMap<>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
configProperties.put(key, value);
}
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
connectionProvider.configure(properties);
connectionProvider.configure(configProperties);
return connectionProvider;
}

View File

@ -7,7 +7,7 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import javax.persistence.PersistenceException;
import jakarta.persistence.PersistenceException;
import org.hibernate.HibernateException;
import org.hibernate.Session;

View File

@ -12,5 +12,3 @@ hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory

View File

@ -4,7 +4,7 @@ hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop

View File

@ -26,7 +26,7 @@
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<artifactId>hibernate-types-60</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
<dependency>
@ -41,9 +41,9 @@
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${org.glassfish.javax.el.version}</version>
<groupId>org.glassfish.expressly</groupId>
<artifactId>expressly</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>javax.money</groupId>
@ -66,16 +66,27 @@
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jakarta-xmlbind-annotations</artifactId>
<version>${jackson-module-jakarta-xmlbind-annotation}</version>
</dependency>
<dependency>
<groupId>org.openjdk.nashorn</groupId>
<artifactId>nashorn-core</artifactId>
<version>15.4</version>
</dependency>
</dependencies>
<properties>
<h2.version>1.4.197</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
<hibernate.version>5.4.12.Final</hibernate.version>
<hibernate-types.version>2.10.4</hibernate-types.version>
<hibernate-validator.version>6.0.16.Final</hibernate-validator.version>
<h2.version>2.1.214</h2.version> <!-- needs to be specified as it fails with parent's 1.4.200 -->
<hibernate.version>6.1.7.Final</hibernate.version>
<hibernate-types.version>2.21.1</hibernate-types.version>
<hibernate-validator.version>8.0.0.Final</hibernate-validator.version>
<org.glassfish.javax.el.version>3.0.1-b11</org.glassfish.javax.el.version>
<money-api.version>1.0.3</money-api.version>
<moneta.version>1.3</moneta.version>
<money-api.version>1.1</money-api.version>
<moneta.version>1.4.2</moneta.version>
<jackson-module-jakarta-xmlbind-annotation>2.14.2</jackson-module-jakarta-xmlbind-annotation>
</properties>
</project>

View File

@ -21,6 +21,7 @@ import com.baeldung.hibernate.pojo.inheritance.Animal;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
import com.baeldung.hibernate.pojo.inheritance.Laptop;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
import com.baeldung.hibernate.pojo.inheritance.Pen;
@ -79,6 +80,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(Laptop.class);
metadataSources.addAnnotatedClass(Book.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(MyEmployee.class);
@ -87,7 +89,6 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();

View File

@ -7,60 +7,57 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.Objects;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
public class CustomIntegerArrayType implements UserType {
public class CustomIntegerArrayType implements UserType<Integer[]> {
@Override
public int[] sqlTypes() {
return new int[]{Types.ARRAY};
public int getSqlType() {
return Types.ARRAY;
}
@Override
public Class returnedClass() {
public Class<Integer[]> returnedClass() {
return Integer[].class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public boolean equals(Integer[] x, Integer[] y) {
if (x instanceof Integer[] && y instanceof Integer[]) {
return Arrays.deepEquals((Integer[])x, (Integer[])y);
return Arrays.deepEquals(x, y);
} else {
return false;
}
}
@Override
public int hashCode(Object x) throws HibernateException {
return Arrays.hashCode((Integer[])x);
public int hashCode(Integer[] x) {
return Arrays.hashCode(x);
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
Array array = rs.getArray(names[0]);
return array != null ? array.getArray() : null;
public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Array array = rs.getArray(position);
return array != null ? (Integer[]) array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value != null && st != null) {
Array array = session.connection().createArrayOf("int", (Integer[])value);
public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException {
if (st != null) {
if (value != null) {
Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value);
st.setArray(index, array);
} else {
st.setNull(index, sqlTypes()[0]);
st.setNull(index, Types.ARRAY);
}
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
Integer[] arr = (Integer[]) value;
return arr != null ? Arrays.copyOf(arr, arr.length) : null;
public Integer[] deepCopy(Integer[] value) {
return value != null ? Arrays.copyOf(value, value.length) : null;
}
@Override
@ -69,18 +66,18 @@ public class CustomIntegerArrayType implements UserType {
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
public Serializable disassemble(Integer[] value) {
return value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
public Integer[] assemble(Serializable cached, Object owner) {
return (Integer[]) cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) {
return detached;
}
}

View File

@ -7,60 +7,57 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.Objects;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
public class CustomStringArrayType implements UserType {
public class CustomStringArrayType implements UserType<String[]> {
@Override
public int[] sqlTypes() {
return new int[]{Types.ARRAY};
public int getSqlType() {
return Types.ARRAY;
}
@Override
public Class returnedClass() {
public Class<String[]> returnedClass() {
return String[].class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
public boolean equals(String[] x, String[] y) {
if (x instanceof String[] && y instanceof String[]) {
return Arrays.deepEquals((String[])x, (String[])y);
return Arrays.deepEquals(x, y);
} else {
return false;
}
}
@Override
public int hashCode(Object x) throws HibernateException {
return Arrays.hashCode((String[])x);
public int hashCode(String[] x) {
return Arrays.hashCode(x);
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
Array array = rs.getArray(names[0]);
return array != null ? array.getArray() : null;
public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Array array = rs.getArray(position);
return array != null ? (String[]) array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value != null && st != null) {
Array array = session.connection().createArrayOf("text", (String[])value);
public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException {
if (st != null) {
if (value != null) {
Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value);
st.setArray(index, array);
} else {
st.setNull(index, sqlTypes()[0]);
st.setNull(index, Types.ARRAY);
}
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
String[] arr = (String[]) value;
return arr != null ? Arrays.copyOf(arr, arr.length) : null;
public String[] deepCopy(String[] value) {
return value != null ? Arrays.copyOf(value, value.length) : null;
}
@Override
@ -69,18 +66,18 @@ public class CustomStringArrayType implements UserType {
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
public Serializable disassemble(String[] value) {
return value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
public String[] assemble(Serializable cached, Object owner) {
return (String[]) cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
public String[] replace(String[] detached, String[] managed, Object owner) {
return detached;
}
}

View File

@ -1,21 +1,13 @@
package com.baeldung.hibernate.arraymapping;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.hibernate.annotations.Type;
import com.vladmihalcea.hibernate.type.array.StringArrayType;
import org.hibernate.annotations.*;
@TypeDefs({
@TypeDef(
name = "string-array",
typeClass = StringArrayType.class
)
})
@Entity
public class User {
@ -25,14 +17,14 @@ public class User {
private String name;
@Column(columnDefinition = "text[]")
@Type(type = "com.baeldung.hibernate.arraymapping.CustomStringArrayType")
@Type(value = com.baeldung.hibernate.arraymapping.CustomStringArrayType.class)
private String[] roles;
@Column(columnDefinition = "int[]")
@Type(type = "com.baeldung.hibernate.arraymapping.CustomIntegerArrayType")
@Type(value = com.baeldung.hibernate.arraymapping.CustomIntegerArrayType.class)
private Integer[] locations;
@Type(type = "string-array")
@Type(StringArrayType.class)
@Column(
name = "phone_numbers",
columnDefinition = "text[]"

View File

@ -1,10 +1,9 @@
package com.baeldung.hibernate.basicannotation;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import jakarta.persistence.Basic;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
@Entity
public class Course {

View File

@ -2,7 +2,7 @@ package com.baeldung.hibernate.entities;
import java.util.List;
import javax.persistence.*;
import jakarta.persistence.*;
@Entity
public class Department {

View File

@ -1,13 +1,13 @@
package com.baeldung.hibernate.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :designation"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),

View File

@ -3,10 +3,10 @@ package com.baeldung.hibernate.fetchMode;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;
import java.util.HashSet;
import java.util.Set;

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