Merge branch 'eugenp:master' into master
This commit is contained in:
		
						commit
						a3acf733da
					
				| @ -7,3 +7,4 @@ You can build the project from the command line using: *mvn clean install*, or i | |||||||
| 
 | 
 | ||||||
| ### Relevant Articles: | ### Relevant Articles: | ||||||
| - [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running) | - [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running) | ||||||
|  | - [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers) | ||||||
|  | |||||||
| @ -30,6 +30,16 @@ | |||||||
|                 </exclusion> |                 </exclusion> | ||||||
|             </exclusions> |             </exclusions> | ||||||
|         </dependency> |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.dhatim</groupId> | ||||||
|  |             <artifactId>fastexcel</artifactId> | ||||||
|  |             <version>${fastexcel.version}</version> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.dhatim</groupId> | ||||||
|  |             <artifactId>fastexcel-reader</artifactId> | ||||||
|  |             <version>${fastexcel.version}</version> | ||||||
|  |         </dependency> | ||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
|     <build> |     <build> | ||||||
| @ -52,6 +62,7 @@ | |||||||
|     <properties> |     <properties> | ||||||
|         <poi.version>5.2.0</poi.version> |         <poi.version>5.2.0</poi.version> | ||||||
|         <jexcel.version>1.0.6</jexcel.version> |         <jexcel.version>1.0.6</jexcel.version> | ||||||
|  |         <fastexcel.version>0.15.3</fastexcel.version> | ||||||
|         <maven.resources.plugin.version>3.2.0</maven.resources.plugin.version> |         <maven.resources.plugin.version>3.2.0</maven.resources.plugin.version> | ||||||
|     </properties> |     </properties> | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -0,0 +1,63 @@ | |||||||
|  | package com.baeldung.fastexcel; | ||||||
|  | 
 | ||||||
|  | import org.dhatim.fastexcel.Workbook; | ||||||
|  | import org.dhatim.fastexcel.Worksheet; | ||||||
|  | import org.dhatim.fastexcel.reader.Cell; | ||||||
|  | import org.dhatim.fastexcel.reader.ReadableWorkbook; | ||||||
|  | import org.dhatim.fastexcel.reader.Row; | ||||||
|  | import org.dhatim.fastexcel.reader.Sheet; | ||||||
|  | 
 | ||||||
|  | import java.io.File; | ||||||
|  | import java.io.FileInputStream; | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.io.OutputStream; | ||||||
|  | import java.nio.file.Files; | ||||||
|  | import java.nio.file.Paths; | ||||||
|  | import java.util.ArrayList; | ||||||
|  | import java.util.HashMap; | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.Map; | ||||||
|  | import java.util.stream.Stream; | ||||||
|  | 
 | ||||||
|  | public class FastexcelHelper { | ||||||
|  | 
 | ||||||
|  |     public Map<Integer, List<String>> readExcel(String fileLocation) throws IOException { | ||||||
|  |         Map<Integer, List<String>> data = new HashMap<>(); | ||||||
|  | 
 | ||||||
|  |         try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) { | ||||||
|  |             Sheet sheet = wb.getFirstSheet(); | ||||||
|  |             try (Stream<Row> rows = sheet.openStream()) { | ||||||
|  |                 rows.forEach(r -> { | ||||||
|  |                     data.put(r.getRowNum(), new ArrayList<>()); | ||||||
|  | 
 | ||||||
|  |                     for (Cell cell : r) { | ||||||
|  |                         data.get(r.getRowNum()).add(cell.getRawValue()); | ||||||
|  |                     } | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  | 
 | ||||||
|  |         return data; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     public void writeExcel() throws IOException { | ||||||
|  |         File currDir = new File("."); | ||||||
|  |         String path = currDir.getAbsolutePath(); | ||||||
|  |         String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx"; | ||||||
|  | 
 | ||||||
|  |         try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) { | ||||||
|  |             Worksheet ws = wb.newWorksheet("Sheet 1"); | ||||||
|  | 
 | ||||||
|  |             ws.width(0, 25); | ||||||
|  |             ws.width(1, 15); | ||||||
|  | 
 | ||||||
|  |             ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set(); | ||||||
|  |             ws.value(0, 0, "Name"); | ||||||
|  |             ws.value(0, 1, "Age"); | ||||||
|  | 
 | ||||||
|  |             ws.range(2, 0, 2, 1).style().wrapText(true).set(); | ||||||
|  |             ws.value(2, 0, "John Smith"); | ||||||
|  |             ws.value(2, 1, 20L); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,49 @@ | |||||||
|  | package com.baeldung.fastexcel; | ||||||
|  | 
 | ||||||
|  | import org.junit.After; | ||||||
|  | import org.junit.Before; | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | import java.io.File; | ||||||
|  | import java.io.IOException; | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.Map; | ||||||
|  | 
 | ||||||
|  | import static org.junit.Assert.assertEquals; | ||||||
|  | 
 | ||||||
|  | public class FastexcelIntegrationTest { | ||||||
|  | 
 | ||||||
|  |     private FastexcelHelper fastexcelHelper; | ||||||
|  |     private static String FILE_NAME = "fastexcel.xlsx"; | ||||||
|  |     private String fileLocation; | ||||||
|  | 
 | ||||||
|  |     @Before | ||||||
|  |     public void generateExcelFile() throws IOException { | ||||||
|  | 
 | ||||||
|  |         File currDir = new File("."); | ||||||
|  |         String path = currDir.getAbsolutePath(); | ||||||
|  |         fileLocation = path.substring(0, path.length() - 1) + FILE_NAME; | ||||||
|  | 
 | ||||||
|  |         fastexcelHelper = new FastexcelHelper(); | ||||||
|  |         fastexcelHelper.writeExcel(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void whenParsingExcelFile_thenCorrect() throws IOException { | ||||||
|  |         Map<Integer, List<String>> data = fastexcelHelper.readExcel(fileLocation); | ||||||
|  | 
 | ||||||
|  |         assertEquals("Name", data.get(1).get(0)); | ||||||
|  |         assertEquals("Age", data.get(1).get(1)); | ||||||
|  | 
 | ||||||
|  |         assertEquals("John Smith", data.get(3).get(0)); | ||||||
|  |         assertEquals("20", data.get(3).get(1)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @After | ||||||
|  |     public void cleanup() { | ||||||
|  |         File testFile = new File(fileLocation); | ||||||
|  |         if (testFile.exists()) { | ||||||
|  |             testFile.delete(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -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; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,44 @@ | |||||||
|  | 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; | ||||||
|  | 
 | ||||||
|  | public class AWSS3ObjectIntegrationTest { | ||||||
|  | 
 | ||||||
|  |     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"); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -12,3 +12,4 @@ This module contains articles about Java array fundamentals. They assume no prev | |||||||
| - [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end) | - [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end) | ||||||
| - [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array) | - [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array) | ||||||
| - [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index) | - [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index) | ||||||
|  | - [Comparing Two Byte Arrays in Java](https://www.baeldung.com/java-comparing-byte-arrays) | ||||||
|  | |||||||
| @ -1,6 +1,9 @@ | |||||||
| package com.baeldung.producerconsumer; | package com.baeldung.producerconsumer; | ||||||
| 
 | 
 | ||||||
|  | import java.util.logging.Logger; | ||||||
|  | 
 | ||||||
| public class Consumer implements Runnable { | public class Consumer implements Runnable { | ||||||
|  |     private static final Logger log = Logger.getLogger(Consumer.class.getCanonicalName()); | ||||||
|     private final DataQueue dataQueue; |     private final DataQueue dataQueue; | ||||||
| 
 | 
 | ||||||
|     public Consumer(DataQueue dataQueue) { |     public Consumer(DataQueue dataQueue) { | ||||||
| @ -14,7 +17,7 @@ public class Consumer implements Runnable { | |||||||
| 
 | 
 | ||||||
|     public void consume() { |     public void consume() { | ||||||
|         while (dataQueue.runFlag) { |         while (dataQueue.runFlag) { | ||||||
|             synchronized (this) { |             synchronized (dataQueue) { | ||||||
|                 while (dataQueue.isEmpty() && dataQueue.runFlag) { |                 while (dataQueue.isEmpty() && dataQueue.runFlag) { | ||||||
|                     try { |                     try { | ||||||
|                         dataQueue.waitOnEmpty(); |                         dataQueue.waitOnEmpty(); | ||||||
| @ -31,12 +34,13 @@ public class Consumer implements Runnable { | |||||||
|                 useMessage(message); |                 useMessage(message); | ||||||
|             } |             } | ||||||
|         } |         } | ||||||
|         System.out.println("Consumer Stopped"); |         log.info("Consumer Stopped"); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private void useMessage(Message message) { |     private void useMessage(Message message) { | ||||||
|         if (message != null) { |         if (message != null) { | ||||||
|             System.out.printf("[%s] Consuming Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData()); |             log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n", | ||||||
|  |                 Thread.currentThread().getName(), message.getId(), message.getData())); | ||||||
| 
 | 
 | ||||||
|             //Sleeping on random time to make it realistic |             //Sleeping on random time to make it realistic | ||||||
|             ThreadUtil.sleep((long) (message.getData() * 100)); |             ThreadUtil.sleep((long) (message.getData() * 100)); | ||||||
|  | |||||||
| @ -1,6 +1,9 @@ | |||||||
| package com.baeldung.producerconsumer; | package com.baeldung.producerconsumer; | ||||||
| 
 | 
 | ||||||
|  | import java.util.logging.Logger; | ||||||
|  | 
 | ||||||
| public class Producer implements Runnable { | public class Producer implements Runnable { | ||||||
|  |     private static final Logger log = Logger.getLogger(Producer.class.getCanonicalName()); | ||||||
|     private final DataQueue dataQueue; |     private final DataQueue dataQueue; | ||||||
| 
 | 
 | ||||||
|     private static int idSequence = 0; |     private static int idSequence = 0; | ||||||
| @ -16,7 +19,7 @@ public class Producer implements Runnable { | |||||||
| 
 | 
 | ||||||
|     public void produce() { |     public void produce() { | ||||||
|         while (dataQueue.runFlag) { |         while (dataQueue.runFlag) { | ||||||
|             synchronized (this) { |             synchronized (dataQueue) { | ||||||
|                 while (dataQueue.isFull() && dataQueue.runFlag) { |                 while (dataQueue.isFull() && dataQueue.runFlag) { | ||||||
|                     try { |                     try { | ||||||
|                         dataQueue.waitOnFull(); |                         dataQueue.waitOnFull(); | ||||||
| @ -33,12 +36,13 @@ public class Producer implements Runnable { | |||||||
|                 dataQueue.notifyAllForEmpty(); |                 dataQueue.notifyAllForEmpty(); | ||||||
|             } |             } | ||||||
|         } |         } | ||||||
|         System.out.println("Producer Stopped"); |         log.info("Producer Stopped"); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private Message generateMessage() { |     private Message generateMessage() { | ||||||
|         Message message = new Message(++idSequence, Math.random()); |         Message message = new Message(incrementAndGetId(), Math.random()); | ||||||
|         System.out.printf("[%s] Generated Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData()); |         log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n", | ||||||
|  |             Thread.currentThread().getName(), message.getId(), message.getData())); | ||||||
| 
 | 
 | ||||||
|         //Sleeping on random time to make it realistic |         //Sleeping on random time to make it realistic | ||||||
|         ThreadUtil.sleep((long) (message.getData() * 100)); |         ThreadUtil.sleep((long) (message.getData() * 100)); | ||||||
| @ -46,6 +50,10 @@ public class Producer implements Runnable { | |||||||
|         return message; |         return message; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  |     private static int incrementAndGetId() { | ||||||
|  |         return ++idSequence; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|     public void stop() { |     public void stop() { | ||||||
|         dataQueue.runFlag = false; |         dataQueue.runFlag = false; | ||||||
|         dataQueue.notifyAllForFull(); |         dataQueue.notifyAllForFull(); | ||||||
|  | |||||||
| @ -2,10 +2,12 @@ package com.baeldung.producerconsumer; | |||||||
| 
 | 
 | ||||||
| import java.util.concurrent.BlockingQueue; | import java.util.concurrent.BlockingQueue; | ||||||
| import java.util.concurrent.LinkedBlockingDeque; | import java.util.concurrent.LinkedBlockingDeque; | ||||||
|  | import java.util.logging.Logger; | ||||||
| 
 | 
 | ||||||
| import static com.baeldung.producerconsumer.ThreadUtil.sleep; | import static com.baeldung.producerconsumer.ThreadUtil.sleep; | ||||||
| 
 | 
 | ||||||
| public class SimpleProducerConsumerDemonstrator { | public class SimpleProducerConsumerDemonstrator { | ||||||
|  |     private static final Logger log = Logger.getLogger(SimpleProducerConsumerDemonstrator.class.getCanonicalName()); | ||||||
|     BlockingQueue<Double> blockingQueue = new LinkedBlockingDeque<>(5); |     BlockingQueue<Double> blockingQueue = new LinkedBlockingDeque<>(5); | ||||||
| 
 | 
 | ||||||
|     private void produce() { |     private void produce() { | ||||||
| @ -17,7 +19,7 @@ public class SimpleProducerConsumerDemonstrator { | |||||||
|                 e.printStackTrace(); |                 e.printStackTrace(); | ||||||
|                 break; |                 break; | ||||||
|             } |             } | ||||||
|             System.out.printf("[%s] Value produced: %f\n", Thread.currentThread().getName(), value); |             log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value)); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| @ -31,7 +33,7 @@ public class SimpleProducerConsumerDemonstrator { | |||||||
|                 break; |                 break; | ||||||
|             } |             } | ||||||
|             // Consume value |             // Consume value | ||||||
|             System.out.printf("[%s] Value consumed: %f\n", Thread.currentThread().getName(), value); |             log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value)); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -6,4 +6,5 @@ This module contains articles about basic Java concurrency. | |||||||
| 
 | 
 | ||||||
| - [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception) | - [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception) | ||||||
| - [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await) | - [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await) | ||||||
|  | - [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking) | ||||||
| - [[<-- Prev]](../core-java-concurrency-basic-2) | - [[<-- Prev]](../core-java-concurrency-basic-2) | ||||||
|  | |||||||
| @ -20,7 +20,8 @@ public class RequestProcessorUnitTest { | |||||||
|     void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException { |     void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException { | ||||||
|         String requestId = requestProcessor.processRequest(); |         String requestId = requestProcessor.processRequest(); | ||||||
| 
 | 
 | ||||||
|         Thread.sleep(2000); |         //The sleep value should be greater than the maximum time the request takes to complete | ||||||
|  |         Thread.sleep(2010); | ||||||
| 
 | 
 | ||||||
|         assertEquals("DONE", requestProcessor.getStatus(requestId)); |         assertEquals("DONE", requestProcessor.getStatus(requestId)); | ||||||
|     } |     } | ||||||
| @ -31,7 +32,8 @@ public class RequestProcessorUnitTest { | |||||||
|         String requestId = requestProcessor.processRequest(); |         String requestId = requestProcessor.processRequest(); | ||||||
| 
 | 
 | ||||||
|         Awaitility.await() |         Awaitility.await() | ||||||
|           .atMost(2, TimeUnit.SECONDS) |            //The timeout value should exceed the maximum time the request takes to complete, for the time amount of a poll (500 ms) | ||||||
|  |           .atMost(2501, TimeUnit.MILLISECONDS) | ||||||
|           .pollDelay(500, TimeUnit.MILLISECONDS) |           .pollDelay(500, TimeUnit.MILLISECONDS) | ||||||
|           .until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING"))); |           .until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING"))); | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -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()); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -7,3 +7,4 @@ This module contains articles about core Java input/output(IO) APIs. | |||||||
| - [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input) | - [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input) | ||||||
| - [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path) | - [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) | - [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) | ||||||
|  | |||||||
| @ -1,46 +1,115 @@ | |||||||
| <?xml version="1.0" encoding="UTF-8"?> | <?xml version="1.0" encoding="UTF-8"?> | ||||||
| <project xmlns="http://maven.apache.org/POM/4.0.0" | <project xmlns="http://maven.apache.org/POM/4.0.0" | ||||||
|     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||||||
|     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |     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> |     <modelVersion>4.0.0</modelVersion> | ||||||
|     <artifactId>core-java-io-apis-2</artifactId> |     <artifactId>core-java-io-apis-2</artifactId> | ||||||
|     <name>core-java-io-apis-2</name> |     <name>core-java-io-apis-2</name> | ||||||
|     <packaging>jar</packaging> |     <packaging>jar</packaging> | ||||||
| 
 | 
 | ||||||
|     <parent> |     <parent> | ||||||
|         <groupId>com.baeldung.core-java-modules</groupId> |         <groupId>com.baeldung.core-java-modules</groupId> | ||||||
|         <artifactId>core-java-modules</artifactId> |         <artifactId>core-java-modules</artifactId> | ||||||
|         <version>0.0.1-SNAPSHOT</version> |         <version>0.0.1-SNAPSHOT</version> | ||||||
|     </parent> |     </parent> | ||||||
| 
 | 
 | ||||||
|     <dependencies> |     <dependencies> | ||||||
|         <!-- logging --> |         <!-- logging --> | ||||||
|         <dependency> |         <dependency> | ||||||
|             <groupId>log4j</groupId> |             <groupId>log4j</groupId> | ||||||
|             <artifactId>log4j</artifactId> |             <artifactId>log4j</artifactId> | ||||||
|             <version>${log4j.version}</version> |             <version>${log4j.version}</version> | ||||||
|         </dependency> |         </dependency> | ||||||
|         <dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly --> |         <dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly --> | ||||||
|             <groupId>org.slf4j</groupId> |             <groupId>org.slf4j</groupId> | ||||||
|             <artifactId>log4j-over-slf4j</artifactId> |             <artifactId>log4j-over-slf4j</artifactId> | ||||||
|             <version>${org.slf4j.version}</version> |             <version>${org.slf4j.version}</version> | ||||||
|         </dependency> |         </dependency> | ||||||
|         <dependency> |         <dependency> | ||||||
|             <groupId>org.projectlombok</groupId> |             <groupId>org.projectlombok</groupId> | ||||||
|             <artifactId>lombok</artifactId> |             <artifactId>lombok</artifactId> | ||||||
|             <version>${lombok.version}</version> |             <version>${lombok.version}</version> | ||||||
|             <scope>provided</scope> |             <scope>provided</scope> | ||||||
|         </dependency> |         </dependency> | ||||||
|     </dependencies> |         <dependency> | ||||||
| 
 |             <groupId>org.junit.jupiter</groupId> | ||||||
|     <build> |             <artifactId>junit-jupiter-engine</artifactId> | ||||||
|         <finalName>core-java-io-apis-2</finalName> |             <version>5.7.2</version> | ||||||
|         <resources> |             <scope>test</scope> | ||||||
|             <resource> |         </dependency> | ||||||
|                 <directory>src/main/resources</directory> |         <dependency> | ||||||
|                 <filtering>true</filtering> |             <groupId>org.junit.jupiter</groupId> | ||||||
|             </resource> |             <artifactId>junit-jupiter</artifactId> | ||||||
|         </resources> |         </dependency> | ||||||
|     </build> |         <dependency> | ||||||
| 
 |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter</artifactId> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter</artifactId> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter</artifactId> | ||||||
|  |         </dependency> | ||||||
|  |         <!-- this is all you need to write tests with JUnit Jupiter --> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter-api</artifactId> | ||||||
|  |             <version>${junit-jupiter-version}</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |         <!-- this dependency is needed to create parameterized tests --> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter-params</artifactId> | ||||||
|  |             <version>${junit-jupiter-version}</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |         <!-- contains the engine that actually runs the Jupiter-tests --> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter-engine</artifactId> | ||||||
|  |             <version>${junit-jupiter-version}</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter</artifactId> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter</artifactId> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.junit.jupiter</groupId> | ||||||
|  |             <artifactId>junit-jupiter</artifactId> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.testng</groupId> | ||||||
|  |             <artifactId>testng</artifactId> | ||||||
|  |             <version>7.1.0</version> | ||||||
|  |             <scope>test</scope> | ||||||
|  |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>org.testng</groupId> | ||||||
|  |             <artifactId>testng</artifactId> | ||||||
|  |             <version>7.5</version> | ||||||
|  |             <scope>compile</scope> | ||||||
|  |         </dependency> | ||||||
|  |     </dependencies> | ||||||
|  |     <properties> | ||||||
|  |         <junit-jupiter-version>5.2.0</junit-jupiter-version> | ||||||
|  |     </properties> | ||||||
|  |     <build> | ||||||
|  |         <finalName>core-java-io-apis-2</finalName> | ||||||
|  |         <resources> | ||||||
|  |             <resource> | ||||||
|  |                 <directory>src/main/resources</directory> | ||||||
|  |                 <filtering>true</filtering> | ||||||
|  |             </resource> | ||||||
|  |         </resources> | ||||||
|  |     </build> | ||||||
|  | 
 | ||||||
| </project> | </project> | ||||||
| @ -0,0 +1,36 @@ | |||||||
|  | package com.baeldung.multinput; | ||||||
|  | 
 | ||||||
|  | import java.util.InputMismatchException; | ||||||
|  | import java.util.Scanner; | ||||||
|  | 
 | ||||||
|  | public class MultiInputs { | ||||||
|  |     public void UsingSpaceDelimiter(){ | ||||||
|  |         Scanner scanner = new Scanner(System.in); | ||||||
|  |         System.out.print("Enter two numbers: "); | ||||||
|  |         int num1 = scanner.nextInt(); | ||||||
|  |         int num2 = scanner.nextInt(); | ||||||
|  |         System.out.println("You entered " + num1 + " and " + num2); | ||||||
|  | 
 | ||||||
|  |     } | ||||||
|  |     public void UsingREDelimiter(){ | ||||||
|  |         Scanner scanner = new Scanner(System.in); | ||||||
|  |         scanner.useDelimiter("[\\s,]+"); | ||||||
|  |         System.out.print("Enter two numbers separated by a space or a comma: "); | ||||||
|  |         int num1 = scanner.nextInt(); | ||||||
|  |         int num2 = scanner.nextInt(); | ||||||
|  |         System.out.println("You entered " + num1 + " and " + num2); | ||||||
|  | 
 | ||||||
|  |     } | ||||||
|  |     public void UsingCustomDelimiter(){ | ||||||
|  |         Scanner scanner = new Scanner(System.in); | ||||||
|  |         scanner.useDelimiter(";"); | ||||||
|  |         System.out.print("Enter two numbers separated by a semicolon: "); | ||||||
|  |         try { int num1 = scanner.nextInt(); | ||||||
|  |             int num2 = scanner.nextInt(); | ||||||
|  |             System.out.println("You entered " + num1 + " and " + num2); } | ||||||
|  |         catch (InputMismatchException e) | ||||||
|  |         { System.out.println("Invalid input. Please enter two integers separated by a semicolon."); } | ||||||
|  | 
 | ||||||
|  |     } | ||||||
|  | } | ||||||
|  | 
 | ||||||
| @ -1,93 +1,92 @@ | |||||||
| package com.baeldung.absolutetorelative; | package com.baeldung.absolutetorelative; | ||||||
| 
 | 
 | ||||||
| import org.assertj.core.api.Assertions; | import java.net.URI; | ||||||
| import org.junit.jupiter.api.Test; | import java.nio.file.Path; | ||||||
| 
 | import java.nio.file.Paths; | ||||||
| import java.net.URI; | import org.junit.jupiter.api.Assertions; | ||||||
| import java.nio.file.Path; | import org.junit.jupiter.api.Test; | ||||||
| import java.nio.file.Paths; | 
 | ||||||
| 
 | public class AbsoluteToRelativeUnitTest { | ||||||
| public class AbsoluteToRelativeUnitTest { | 
 | ||||||
| 
 |     // given - until using Paths, no need to create physical files | ||||||
|     // given - until using Paths, no need to create physical files |     private final Path pathOne = Paths.get("/baeldung/bar/one.txt"); | ||||||
|     private final Path pathOne = Paths.get("/baeldung/bar/one.txt"); |     private final Path pathTwo = Paths.get("/baeldung/bar/two.txt"); | ||||||
|     private final Path pathTwo = Paths.get("/baeldung/bar/two.txt"); |     private final Path pathThree = Paths.get("/baeldung/foo/three.txt"); | ||||||
|     private final Path pathThree = Paths.get("/baeldung/foo/three.txt"); | 
 | ||||||
| 
 |     private final URI uriOne = pathOne.toUri(); | ||||||
|     private final URI uriOne = pathOne.toUri(); |     private final URI uriTwo = pathTwo.toUri(); | ||||||
|     private final URI uriTwo = pathTwo.toUri(); |     private final URI uriThree = pathThree.toUri(); | ||||||
|     private final URI uriThree = pathThree.toUri(); | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() { | ||||||
|     public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() { |         Path result = pathOne.relativize(pathTwo); | ||||||
|         Path result = pathOne.relativize(pathTwo); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .isRelative() | ||||||
|                 .isRelative() |                 .isEqualTo(Paths.get("../two.txt")); | ||||||
|                 .isEqualTo(Paths.get("../two.txt")); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() { | ||||||
|     public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() { |         Path result = pathTwo.relativize(pathOne); | ||||||
|         Path result = pathTwo.relativize(pathOne); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .isRelative() | ||||||
|                 .isRelative() |                 .isEqualTo(Paths.get("../one.txt")); | ||||||
|                 .isEqualTo(Paths.get("../one.txt")); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() { | ||||||
|     public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() { |         Path result = pathOne.getParent().relativize(pathTwo); | ||||||
|         Path result = pathOne.getParent().relativize(pathTwo); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .isRelative() | ||||||
|                 .isRelative() |                 .isEqualTo(Paths.get("two.txt")); | ||||||
|                 .isEqualTo(Paths.get("two.txt")); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() { | ||||||
|     public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() { |         Path result = pathOne.relativize(pathThree); | ||||||
|         Path result = pathOne.relativize(pathThree); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .isRelative() | ||||||
|                 .isRelative() |                 .isEqualTo(Paths.get("../../foo/three.txt")); | ||||||
|                 .isEqualTo(Paths.get("../../foo/three.txt")); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() { | ||||||
|     public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() { |         Path result = pathThree.relativize(pathOne); | ||||||
|         Path result = pathThree.relativize(pathOne); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .isRelative() | ||||||
|                 .isRelative() |                 .isEqualTo(Paths.get("../../bar/one.txt")); | ||||||
|                 .isEqualTo(Paths.get("../../bar/one.txt")); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() { | ||||||
|     public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() { |         URI result = uriOne.relativize(uriTwo); | ||||||
|         URI result = uriOne.relativize(uriTwo); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .asString() | ||||||
|                 .asString() |                 .contains("/baeldung/bar/two.txt"); | ||||||
|                 .contains("/baeldung/bar/two.txt"); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() { | ||||||
|     public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() { |         URI result = pathOne.getParent().toUri().relativize(uriTwo); | ||||||
|         URI result = pathOne.getParent().toUri().relativize(uriTwo); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .asString() | ||||||
|                 .asString() |                 .contains("two.txt"); | ||||||
|                 .contains("two.txt"); |     } | ||||||
|     } | 
 | ||||||
| 
 |     @Test | ||||||
|     @Test |     public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() { | ||||||
|     public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() { |         URI result = pathOne.getParent().toUri().relativize(uriThree); | ||||||
|         URI result = pathOne.getParent().toUri().relativize(uriThree); | 
 | ||||||
| 
 |         org.assertj.core.api.Assertions.assertThat(result) | ||||||
|         Assertions.assertThat(result) |                 .asString() | ||||||
|                 .asString() |                 .contains("/baeldung/foo/three.txt"); | ||||||
|                 .contains("/baeldung/foo/three.txt"); |     } | ||||||
|     } | 
 | ||||||
| 
 | } | ||||||
| } |  | ||||||
|  | |||||||
| @ -1,31 +1,31 @@ | |||||||
| package com.baeldung.bufferedreadervsfilereader; | package com.baeldung.bufferedreadervsfilereader; | ||||||
| 
 | 
 | ||||||
| import org.junit.Test; | import static org.junit.jupiter.api.Assertions.assertEquals; | ||||||
| 
 | 
 | ||||||
| import static org.junit.jupiter.api.Assertions.assertEquals; | import java.io.BufferedReader; | ||||||
| 
 | import java.io.FileReader; | ||||||
| import java.io.BufferedReader; | import java.io.IOException; | ||||||
| import java.io.FileReader; | 
 | ||||||
| import java.io.IOException; | import org.junit.jupiter.api.Assertions; | ||||||
| 
 | import org.testng.annotations.Test; | ||||||
| public class BufferedReaderUnitTest { | public class BufferedReaderUnitTest { | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenReadingAFile_thenReadsLineByLine() { |     public void whenReadingAFile_thenReadsLineByLine() { | ||||||
|         StringBuilder result = new StringBuilder(); |         StringBuilder result = new StringBuilder(); | ||||||
| 
 | 
 | ||||||
|         try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) { |         try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) { | ||||||
|             String line; |             String line; | ||||||
| 
 | 
 | ||||||
|             while((line = br.readLine()) != null) { |             while((line = br.readLine()) != null) { | ||||||
|                 result.append(line); |                 result.append(line); | ||||||
|                 result.append('\n'); |                 result.append('\n'); | ||||||
|             } |             } | ||||||
|         } catch (IOException e) { |         } catch (IOException e) { | ||||||
|             e.printStackTrace(); |             e.printStackTrace(); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         assertEquals("first line\nsecond line\nthird line\n", result.toString()); |         assertEquals("first line\nsecond line\nthird line\n", result.toString()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,30 +1,30 @@ | |||||||
| package com.baeldung.bufferedreadervsfilereader; | package com.baeldung.bufferedreadervsfilereader; | ||||||
| 
 | 
 | ||||||
| import org.junit.jupiter.api.Test; | import static org.junit.jupiter.api.Assertions.assertEquals; | ||||||
| 
 | 
 | ||||||
| import java.io.FileReader; | import java.io.FileReader; | ||||||
| import java.io.IOException; | import java.io.IOException; | ||||||
| 
 | 
 | ||||||
| import static org.junit.jupiter.api.Assertions.assertEquals; | import org.junit.jupiter.api.Test; | ||||||
| 
 | 
 | ||||||
| public class FileReaderUnitTest { | public class FileReaderUnitTest { | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenReadingAFile_thenReadsCharByChar() { |     public void whenReadingAFile_thenReadsCharByChar() { | ||||||
|         StringBuilder result = new StringBuilder(); |         StringBuilder result = new StringBuilder(); | ||||||
| 
 | 
 | ||||||
|         try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) { |         try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) { | ||||||
|             int i = fr.read(); |             int i = fr.read(); | ||||||
| 
 | 
 | ||||||
|             while(i != -1) { |             while(i != -1) { | ||||||
|                 result.append((char)i); |                 result.append((char)i); | ||||||
| 
 | 
 | ||||||
|                 i = fr.read(); |                 i = fr.read(); | ||||||
|             } |             } | ||||||
|         } catch (IOException e) { |         } catch (IOException e) { | ||||||
|             e.printStackTrace(); |             e.printStackTrace(); | ||||||
|         } |         } | ||||||
| 
 | 
 | ||||||
|         assertEquals("qwerty", result.toString()); |         assertEquals("qwerty", result.toString()); | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -0,0 +1,47 @@ | |||||||
|  | package com.baeldung.multinput; | ||||||
|  |     import java.io.ByteArrayInputStream; | ||||||
|  |     import java.io.InputStream; | ||||||
|  |     import java.util.InputMismatchException; | ||||||
|  |     import org.junit.jupiter.api.Assertions; | ||||||
|  |     import org.testng.annotations.Test; | ||||||
|  | import com.baeldung.multinput.MultiInputs; | ||||||
|  | public class TestMultipleInputsUnitTest { | ||||||
|  |     @Test | ||||||
|  |     public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() { | ||||||
|  |         String input = "10 20\n"; | ||||||
|  |         InputStream in = new ByteArrayInputStream(input.getBytes()); | ||||||
|  |         System.setIn(in); | ||||||
|  |         MultiInputs mi = new MultiInputs(); | ||||||
|  |         mi.UsingSpaceDelimiter(); | ||||||
|  |         // You can add assertions here to verify the behavior of the method | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() { | ||||||
|  |         String input = "30, 40\n"; | ||||||
|  |         InputStream in = new ByteArrayInputStream(input.getBytes()); | ||||||
|  |         System.setIn(in); | ||||||
|  |         MultiInputs mi = new MultiInputs(); | ||||||
|  |         mi.UsingREDelimiter(); | ||||||
|  |         // You can add assertions here to verify the behavior of the method | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() { | ||||||
|  |         String input = "50; 60\n"; | ||||||
|  |         InputStream in = new ByteArrayInputStream(input.getBytes()); | ||||||
|  |         System.setIn(in); | ||||||
|  |         MultiInputs mi = new MultiInputs(); | ||||||
|  |         mi.UsingCustomDelimiter(); | ||||||
|  |         // You can add assertions here to verify the behavior of the method | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() { | ||||||
|  |         String input = "abc\n"; | ||||||
|  |         InputStream in = new ByteArrayInputStream(input.getBytes()); | ||||||
|  |         System.setIn(in); | ||||||
|  |         MultiInputs mi = new MultiInputs(); | ||||||
|  |         Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -1,29 +1,27 @@ | |||||||
| package com.baeldung.path; | package com.baeldung.path; | ||||||
| 
 | 
 | ||||||
| import org.junit.jupiter.api.Test; | import java.io.File; | ||||||
| 
 | 
 | ||||||
| import java.io.File; | import javax.swing.filechooser.FileSystemView; | ||||||
| 
 | 
 | ||||||
| import static org.junit.Assert.assertEquals; | import org.junit.jupiter.api.Test; | ||||||
| 
 | 
 | ||||||
| import javax.swing.filechooser.FileSystemView; | public class DesktopPathUnitTest { | ||||||
| 
 |     // Adapt DESKTOP_PATH variable to your own system path | ||||||
| public class DesktopPathUnitTest { |     // private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop"; | ||||||
|     // Adapt DESKTOP_PATH variable to your own system path | 
 | ||||||
|     // private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop"; |     @Test | ||||||
| 
 |     public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() { | ||||||
|     @Test |         String desktopPath = System.getProperty("user.home") + File.separator + "Desktop"; | ||||||
|     public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() { |         // assertEquals(DESKTOP_PATH, desktopPath); | ||||||
|         String desktopPath = System.getProperty("user.home") + File.separator + "Desktop"; |     } | ||||||
|         // assertEquals(DESKTOP_PATH, desktopPath); | 
 | ||||||
|     } |     @Test | ||||||
| 
 |     public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() { | ||||||
|     @Test |         FileSystemView view = FileSystemView.getFileSystemView(); | ||||||
|     public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() { |         File file = view.getHomeDirectory(); | ||||||
|         FileSystemView view = FileSystemView.getFileSystemView(); |         String path = file.getPath(); | ||||||
|         File file = view.getHomeDirectory(); |         // assertEquals(DESKTOP_PATH, path); | ||||||
|         String path = file.getPath(); |     } | ||||||
|         // assertEquals(DESKTOP_PATH, path); | 
 | ||||||
|     } | } | ||||||
| 
 |  | ||||||
| } |  | ||||||
|  | |||||||
| @ -1,85 +1,85 @@ | |||||||
| package com.baeldung.scanner; | package com.baeldung.scanner; | ||||||
| 
 | 
 | ||||||
| import static org.junit.jupiter.api.Assertions.assertEquals; | import static org.junit.jupiter.api.Assertions.assertEquals; | ||||||
| import static org.junit.jupiter.api.Assertions.assertThrows; | import static org.junit.jupiter.api.Assertions.assertThrows; | ||||||
| 
 | 
 | ||||||
| import java.util.InputMismatchException; | import java.util.InputMismatchException; | ||||||
| import java.util.Scanner; | import java.util.Scanner; | ||||||
| 
 | 
 | ||||||
| import org.junit.jupiter.api.Test; | import org.junit.jupiter.api.Test; | ||||||
| 
 | 
 | ||||||
| public class NextLineVsNextIntUnitTest { | public class NextLineVsNextIntUnitTest { | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() { |     void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() { | ||||||
|         String input = "42\n"; |         String input = "42\n"; | ||||||
| 
 | 
 | ||||||
|         //nextLine() |         //nextLine() | ||||||
|         Scanner sc1 = new Scanner(input); |         Scanner sc1 = new Scanner(input); | ||||||
|         int num1 = Integer.parseInt(sc1.nextLine()); |         int num1 = Integer.parseInt(sc1.nextLine()); | ||||||
|         assertEquals(42, num1); |         assertEquals(42, num1); | ||||||
| 
 | 
 | ||||||
|         //nextInt() |         //nextInt() | ||||||
|         Scanner sc2 = new Scanner(input); |         Scanner sc2 = new Scanner(input); | ||||||
|         int num2 = sc2.nextInt(); |         int num2 = sc2.nextInt(); | ||||||
|         assertEquals(42, num2); |         assertEquals(42, num2); | ||||||
| 
 | 
 | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() { |     void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() { | ||||||
|         String input = "Nan\n"; |         String input = "Nan\n"; | ||||||
| 
 | 
 | ||||||
|         //nextLine() -> NumberFormatException |         //nextLine() -> NumberFormatException | ||||||
|         Scanner sc1 = new Scanner(input); |         Scanner sc1 = new Scanner(input); | ||||||
|         assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine())); |         assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine())); | ||||||
| 
 | 
 | ||||||
|         //nextInt() -> InputMismatchException |         //nextInt() -> InputMismatchException | ||||||
|         Scanner sc2 = new Scanner(input); |         Scanner sc2 = new Scanner(input); | ||||||
|         assertThrows(InputMismatchException.class, sc2::nextInt); |         assertThrows(InputMismatchException.class, sc2::nextInt); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() { |     void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() { | ||||||
|         String input = "42 is a magic number\n"; |         String input = "42 is a magic number\n"; | ||||||
| 
 | 
 | ||||||
|         //nextInt() to read '42' |         //nextInt() to read '42' | ||||||
|         Scanner sc2 = new Scanner(input); |         Scanner sc2 = new Scanner(input); | ||||||
|         int num2 = sc2.nextInt(); |         int num2 = sc2.nextInt(); | ||||||
|         assertEquals(42, num2); |         assertEquals(42, num2); | ||||||
| 
 | 
 | ||||||
|         // call nextInt() again on "is" |         // call nextInt() again on "is" | ||||||
|         assertThrows(InputMismatchException.class, sc2::nextInt); |         assertThrows(InputMismatchException.class, sc2::nextInt); | ||||||
| 
 | 
 | ||||||
|         String theNextToken = sc2.next(); |         String theNextToken = sc2.next(); | ||||||
|         assertEquals("is", theNextToken); |         assertEquals("is", theNextToken); | ||||||
| 
 | 
 | ||||||
|         theNextToken = sc2.next(); |         theNextToken = sc2.next(); | ||||||
|         assertEquals("a", theNextToken); |         assertEquals("a", theNextToken); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() { |     void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() { | ||||||
| 
 | 
 | ||||||
|         String input = new StringBuilder().append("42\n") |         String input = new StringBuilder().append("42\n") | ||||||
|           .append("It is a magic number.\n") |           .append("It is a magic number.\n") | ||||||
|           .toString(); |           .toString(); | ||||||
| 
 | 
 | ||||||
|         //nextLine() |         //nextLine() | ||||||
|         Scanner sc1 = new Scanner(input); |         Scanner sc1 = new Scanner(input); | ||||||
|         int num1 = Integer.parseInt(sc1.nextLine()); |         int num1 = Integer.parseInt(sc1.nextLine()); | ||||||
|         String nextLineText1 = sc1.nextLine(); |         String nextLineText1 = sc1.nextLine(); | ||||||
|         assertEquals(42, num1); |         assertEquals(42, num1); | ||||||
|         assertEquals("It is a magic number.", nextLineText1); |         assertEquals("It is a magic number.", nextLineText1); | ||||||
| 
 | 
 | ||||||
|         //nextInt() |         //nextInt() | ||||||
|         Scanner sc2 = new Scanner(input); |         Scanner sc2 = new Scanner(input); | ||||||
|         int num2 = sc2.nextInt(); |         int num2 = sc2.nextInt(); | ||||||
|         assertEquals(42, num2); |         assertEquals(42, num2); | ||||||
| 
 | 
 | ||||||
|         // nextInt() leaves the newline character (\n) behind |         // nextInt() leaves the newline character (\n) behind | ||||||
|         String nextLineText2 = sc2.nextLine(); |         String nextLineText2 = sc2.nextLine(); | ||||||
|         assertEquals("", nextLineText2); |         assertEquals("", nextLineText2); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
| @ -1,38 +1,38 @@ | |||||||
| package com.baeldung.scanner; | package com.baeldung.scanner; | ||||||
| 
 | 
 | ||||||
| import static org.junit.jupiter.api.Assertions.assertEquals; | import static org.junit.jupiter.api.Assertions.assertEquals; | ||||||
| 
 | 
 | ||||||
| import java.util.Scanner; | import java.util.Scanner; | ||||||
| 
 | 
 | ||||||
| import org.junit.jupiter.api.Test; | import org.junit.jupiter.api.Test; | ||||||
| 
 | 
 | ||||||
| public class ScanACharacterUnitTest { | public class ScanACharacterUnitTest { | ||||||
| 
 | 
 | ||||||
|     // given - input scanner source, no need to scan from console |     // given - input scanner source, no need to scan from console | ||||||
|     String input = new StringBuilder().append("abc\n") |     String input = new StringBuilder().append("abc\n") | ||||||
|       .append("mno\n") |       .append("mno\n") | ||||||
|       .append("xyz\n") |       .append("xyz\n") | ||||||
|       .toString(); |       .toString(); | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() { |     public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() { | ||||||
|         Scanner sc = new Scanner(input); |         Scanner sc = new Scanner(input); | ||||||
|         char c = sc.next().charAt(0); |         char c = sc.next().charAt(0); | ||||||
|         assertEquals('a', c); |         assertEquals('a', c); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() { |     public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() { | ||||||
|         Scanner sc = new Scanner(input); |         Scanner sc = new Scanner(input); | ||||||
|         char c = sc.findInLine(".").charAt(0); |         char c = sc.findInLine(".").charAt(0); | ||||||
|         assertEquals('a', c); |         assertEquals('a', c); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() { |     public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() { | ||||||
|         Scanner sc = new Scanner(input); |         Scanner sc = new Scanner(input); | ||||||
|         char c = sc.useDelimiter("").next().charAt(0); |         char c = sc.useDelimiter("").next().charAt(0); | ||||||
|         assertEquals('a', c); |         assertEquals('a', c); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -0,0 +1,107 @@ | |||||||
|  | package com.baeldung.scanner; | ||||||
|  | 
 | ||||||
|  | import static org.junit.jupiter.api.Assertions.assertArrayEquals; | ||||||
|  | import static org.junit.jupiter.api.Assertions.assertEquals; | ||||||
|  | 
 | ||||||
|  | import java.util.ArrayList; | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.Scanner; | ||||||
|  | 
 | ||||||
|  | import org.junit.jupiter.api.Test; | ||||||
|  | 
 | ||||||
|  | import com.google.common.collect.Lists; | ||||||
|  | import com.google.common.collect.ObjectArrays; | ||||||
|  | 
 | ||||||
|  | public class ScannerToArrayUnitTest { | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void whenMultipleElementsInOneLine_thenGetExpectedArray() { | ||||||
|  |         String input = "Java Kotlin Ruby Python Go\n"; | ||||||
|  |         String[] expected = new String[] { "Java", "Kotlin", "Ruby", "Python", "Go" }; | ||||||
|  | 
 | ||||||
|  |         // scanner.next() | ||||||
|  |         Scanner scanner1 = new Scanner(input); | ||||||
|  |         String[] result1 = new String[5]; | ||||||
|  |         int i = 0; | ||||||
|  |         while (i < result1.length) { | ||||||
|  |             result1[i] = scanner1.next(); | ||||||
|  |             i++; | ||||||
|  |         } | ||||||
|  |         assertArrayEquals(expected, result1); | ||||||
|  | 
 | ||||||
|  |         //split() | ||||||
|  |         Scanner scanner2 = new Scanner(input); | ||||||
|  |         String[] result2 = scanner2.nextLine() | ||||||
|  |           .split("\\s+"); | ||||||
|  |         assertArrayEquals(expected, result2); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void whenOneElementPerLine_thenGetExpectedArray() { | ||||||
|  |         String input = new StringBuilder().append("Baeldung Java\n") | ||||||
|  |           .append("Baeldung Kotlin\n") | ||||||
|  |           .append("Baeldung Linux\n") | ||||||
|  |           .toString(); | ||||||
|  | 
 | ||||||
|  |         String[] expected = new String[] { "Baeldung Java", "Baeldung Kotlin", "Baeldung Linux" }; | ||||||
|  | 
 | ||||||
|  |         String[] result = new String[3]; | ||||||
|  |         Scanner scanner = new Scanner(input); | ||||||
|  |         int i = 0; | ||||||
|  |         while (i < result.length) { | ||||||
|  |             result[i] = scanner.nextLine(); | ||||||
|  |             i++; | ||||||
|  |         } | ||||||
|  |         assertArrayEquals(expected, result); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void whenOneElementPerLine_thenGetExpectedList() { | ||||||
|  |         String input = new StringBuilder().append("Baeldung Java\n") | ||||||
|  |           .append("Baeldung Kotlin\n") | ||||||
|  |           .append("Baeldung Linux\n") | ||||||
|  |           .toString(); | ||||||
|  | 
 | ||||||
|  |         List<String> expected = Lists.newArrayList("Baeldung Java", "Baeldung Kotlin", "Baeldung Linux"); | ||||||
|  | 
 | ||||||
|  |         List<String> result = new ArrayList<>(); | ||||||
|  |         Scanner scanner = new Scanner(input); | ||||||
|  |         while (scanner.hasNextLine()) { | ||||||
|  |             result.add(scanner.nextLine()); | ||||||
|  |         } | ||||||
|  |         assertEquals(expected, result); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void whenEveryTokenIsAnElement_thenGetExpectedList() { | ||||||
|  |         String input = new StringBuilder().append("Linux Windows MacOS\n") | ||||||
|  |           .append("Java Kotlin Python Go\n") | ||||||
|  |           .toString(); | ||||||
|  | 
 | ||||||
|  |         List<String> expected = Lists.newArrayList("Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go"); | ||||||
|  |         List<String> result = new ArrayList<>(); | ||||||
|  |         Scanner scanner = new Scanner(input); | ||||||
|  |         while (scanner.hasNext()) { | ||||||
|  |             result.add(scanner.next()); | ||||||
|  |         } | ||||||
|  |         assertEquals(expected, result); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void whenEveryTokenIsAnElement_thenGetExpectedArray() { | ||||||
|  |         String input = new StringBuilder().append("Linux Windows MacOS\n") | ||||||
|  |           .append("Java Kotlin Python Go\n") | ||||||
|  |           .toString(); | ||||||
|  | 
 | ||||||
|  |         String[] expected = new String[] { "Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go" }; | ||||||
|  |         String[] result = new String[] {}; | ||||||
|  | 
 | ||||||
|  |         Scanner scanner = new Scanner(input); | ||||||
|  |         while (scanner.hasNextLine()) { | ||||||
|  |             String[] lineInArray = scanner.nextLine() | ||||||
|  |               .split("\\s+"); | ||||||
|  |             result = ObjectArrays.concat(result, lineInArray, String.class); | ||||||
|  |         } | ||||||
|  |         assertArrayEquals(expected, result); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -1,3 +1,3 @@ | |||||||
| first line | first line | ||||||
| second line | second line | ||||||
| third line | third line | ||||||
|  | |||||||
| @ -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); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -23,7 +23,7 @@ | |||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
|     <properties> |     <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> |     </properties> | ||||||
| 
 | 
 | ||||||
| </project> | </project> | ||||||
| @ -0,0 +1,5 @@ | |||||||
|  | package com.baeldung.interfacesingleimpl; | ||||||
|  | 
 | ||||||
|  | public interface Animal { | ||||||
|  |     String makeSound(); | ||||||
|  | } | ||||||
| @ -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(); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -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; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -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; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -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); | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,8 @@ | |||||||
|  | package com.baeldung.interfacesingleimpl; | ||||||
|  | 
 | ||||||
|  | public class MockAnimal implements Animal { | ||||||
|  |     @Override | ||||||
|  |     public String makeSound() { | ||||||
|  |         return "Mock animal sound!"; | ||||||
|  |     } | ||||||
|  | } | ||||||
							
								
								
									
										2
									
								
								core-java-modules/core-java-records/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								core-java-modules/core-java-records/README.md
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,2 @@ | |||||||
|  | ## Relevant Articles | ||||||
|  | - [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records) | ||||||
| @ -0,0 +1,35 @@ | |||||||
|  | package com.baeldung.regex.z_regexp; | ||||||
|  | 
 | ||||||
|  | import org.junit.jupiter.api.Assertions; | ||||||
|  | import org.junit.jupiter.api.Test; | ||||||
|  | 
 | ||||||
|  | public class ZRegularExpressionUnitTest { | ||||||
|  |     @Test | ||||||
|  |     public void givenCreditCardNumber_thenReturnIfMatched() { | ||||||
|  |         String creditCardNumber = "1234567890123456"; | ||||||
|  |         String pattern = "\\d{16}\\z"; | ||||||
|  |         Assertions.assertTrue(creditCardNumber.matches(pattern)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenLogOutput_thenReturnIfMatched() { | ||||||
|  |         String logLine = "2022-05-01 14:30:00,123 INFO Some log message"; | ||||||
|  |         String pattern = ".*message\\z"; | ||||||
|  |         Assertions.assertTrue(logLine.matches(pattern)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenEmailMessage_thenReturnIfMatched() { | ||||||
|  |         String myMessage = "Hello HR, I hope i can write to Baeldung\n"; | ||||||
|  |         String pattern = ".*Baeldung\\s*\\Z"; | ||||||
|  |         Assertions.assertTrue(myMessage.matches(pattern)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenFileExtension_thenReturnIfMatched() { | ||||||
|  |         String fileName = "image.jpeg"; | ||||||
|  |         String pattern = ".*\\.jpeg\\Z"; | ||||||
|  |         Assertions.assertTrue(fileName.matches(pattern)); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,27 @@ | |||||||
|  | package com.baeldung.nullandempty; | ||||||
|  | 
 | ||||||
|  | import static org.junit.jupiter.api.Assertions.assertTrue; | ||||||
|  | import static org.junit.jupiter.api.Assertions.assertThrows; | ||||||
|  | import static org.junit.jupiter.api.Assertions.assertFalse; | ||||||
|  | 
 | ||||||
|  | import org.junit.jupiter.api.Test; | ||||||
|  | 
 | ||||||
|  | public class NullAndEmptyStringUnitTest { | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenANullAndEmptyString_whenUsingStringMethods_thenShouldGetExpectedResult() { | ||||||
|  |         String nullString = null; | ||||||
|  |         String emptyString = ""; | ||||||
|  |         assertTrue(emptyString.equals("")); | ||||||
|  |         assertThrows(NullPointerException.class, () -> nullString.length()); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenANullAndEmptyString_whenCheckingEquality_thenShouldGetExpectedResult() { | ||||||
|  |         String nullString = null; | ||||||
|  |         String emptyString = ""; | ||||||
|  |         assertFalse(emptyString.equals(nullString)); | ||||||
|  |         assertFalse(emptyString == nullString); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -10,3 +10,5 @@ | |||||||
| - [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace) | - [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace) | ||||||
| - [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number) | - [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number) | ||||||
| - [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes) | - [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes) | ||||||
|  | - [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string) | ||||||
|  | - [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string) | ||||||
|  | |||||||
| @ -0,0 +1,36 @@ | |||||||
|  | package com.baeldung.longestword; | ||||||
|  | 
 | ||||||
|  | import java.util.Arrays; | ||||||
|  | import java.util.Collections; | ||||||
|  | import java.util.Comparator; | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.Optional; | ||||||
|  | import java.util.stream.Collectors; | ||||||
|  | 
 | ||||||
|  | public class LongestWordFinder { | ||||||
|  | 
 | ||||||
|  |     public Optional<String> findLongestWord(String sentence) { | ||||||
|  |         return Optional.ofNullable(sentence) | ||||||
|  |           .filter(string -> !string.trim() | ||||||
|  |             .isEmpty()) | ||||||
|  |           .map(string -> string.split("\\s")) | ||||||
|  |           .map(Arrays::asList) | ||||||
|  |           .map(list -> Collections.max(list, Comparator.comparingInt(String::length))); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     public List<String> findLongestWords(String sentence) { | ||||||
|  |         if (sentence == null || sentence.trim() | ||||||
|  |           .isEmpty()) { | ||||||
|  |             return Collections.emptyList(); | ||||||
|  |         } | ||||||
|  |         String[] words = sentence.split("\\s"); | ||||||
|  |         int maxWordLength = Arrays.stream(words) | ||||||
|  |           .mapToInt(String::length) | ||||||
|  |           .max() | ||||||
|  |           .orElseThrow(); | ||||||
|  |         return Arrays.stream(words) | ||||||
|  |           .filter(word -> word.length() == maxWordLength) | ||||||
|  |           .collect(Collectors.toList()); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,62 @@ | |||||||
|  | package com.baeldung.longestword; | ||||||
|  | 
 | ||||||
|  | import static org.assertj.core.api.Assertions.assertThat; | ||||||
|  | 
 | ||||||
|  | import org.junit.jupiter.api.Test; | ||||||
|  | 
 | ||||||
|  | class LongestWordFinderUnitTest { | ||||||
|  | 
 | ||||||
|  |     LongestWordFinder longestWordFinder = new LongestWordFinder(); | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenNull_whenFindLongestWord_thenEmpty() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWord(null)).isEmpty(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenEmptyString_whenFindLongestWord_thenEmpty() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWord("")).isEmpty(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenStringWithOnlySpaces_whenFindLongestWord_thenEmpty() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWord("   ")).isEmpty(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenAPhraseWithALongestWord_whenFindLongestWord_thenLongestWordOfThePhrase() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWord("This is a phrase with words")).hasValue("phrase"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWord_thenAnyOfTheLongestsWordsOfThePhrase() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWord("Baeldung is another word of size eight in this sentence") | ||||||
|  |           .get()).isIn("Baeldung", "sentence"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenNull_whenFindLongestWords_thenEmpty() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWords(null)).isEmpty(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenEmptyString_whenFindLongestWords_thenEmpty() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWords("")).isEmpty(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenStringWithOnlySpaces_whenFindLongestWords_thenEmpty() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWords("   ")).isEmpty(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenAPhraseWithALongestWord_whenFindLongestWords_thenLongestWordOfThePhrase() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWords("This is a phrase with words")).containsExactly("phrase"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWords_thenAllLongestsWords() { | ||||||
|  |         assertThat(longestWordFinder.findLongestWords("Baeldung is another word of size eight in this sentence")).containsExactly("Baeldung", "sentence"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -0,0 +1,55 @@ | |||||||
|  | package com.baeldung.stringbuilder; | ||||||
|  | 
 | ||||||
|  | import org.openjdk.jmh.annotations.*; | ||||||
|  | import org.openjdk.jmh.runner.Runner; | ||||||
|  | import org.openjdk.jmh.runner.options.Options; | ||||||
|  | import org.openjdk.jmh.runner.options.OptionsBuilder; | ||||||
|  | 
 | ||||||
|  | import java.util.concurrent.TimeUnit; | ||||||
|  | 
 | ||||||
|  | @BenchmarkMode(Mode.SingleShotTime) | ||||||
|  | @OutputTimeUnit(TimeUnit.MILLISECONDS) | ||||||
|  | @Measurement(batchSize = 100000, iterations = 10) | ||||||
|  | @Warmup(batchSize = 100000, iterations = 10) | ||||||
|  | @State(Scope.Thread) | ||||||
|  | public class ReuseStringBuilderPerformance { | ||||||
|  | 
 | ||||||
|  |     @Benchmark | ||||||
|  |     public void benchmarkStringBuilder() { | ||||||
|  |         for (int i = 0; i < 100; i++) { | ||||||
|  |             StringBuilder stringBuilder = new StringBuilder(); | ||||||
|  |             stringBuilder.append("baeldung"); | ||||||
|  |             stringBuilder.toString(); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Benchmark | ||||||
|  |     public void benchmarkStringBuilderReuseWithSetLength() { | ||||||
|  |         StringBuilder stringBuilder = new StringBuilder(); | ||||||
|  |         for (int i = 0; i < 100; i++) { | ||||||
|  |             stringBuilder.append("baeldung"); | ||||||
|  |             stringBuilder.toString(); | ||||||
|  |             stringBuilder.setLength(0); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Benchmark() | ||||||
|  |     public void benchmarkStringBuilderReuseWithDelete() { | ||||||
|  |         StringBuilder stringBuilder = new StringBuilder(); | ||||||
|  |         for (int i = 0; i < 100; i++) { | ||||||
|  |             stringBuilder.append("baeldung"); | ||||||
|  |             stringBuilder.toString(); | ||||||
|  |             stringBuilder.delete(0, stringBuilder.length()); | ||||||
|  |         } | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     public static void main(String[] args) throws Exception { | ||||||
|  |         Options options = new OptionsBuilder() | ||||||
|  |                 .include(ReuseStringBuilderPerformance.class.getSimpleName()).threads(1) | ||||||
|  |                 .forks(1).shouldFailOnError(true) | ||||||
|  |                 .shouldDoGC(true) | ||||||
|  |                 .jvmArgs("-server").build(); | ||||||
|  |         new Runner(options).run(); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  | } | ||||||
| @ -1,9 +1,11 @@ | |||||||
| package com.baeldung.jsonpath.introduction; | package com.baeldung.jsonpath.introduction; | ||||||
| 
 | 
 | ||||||
| import com.jayway.jsonpath.Configuration; | import com.jayway.jsonpath.Configuration; | ||||||
|  | import com.jayway.jsonpath.Criteria; | ||||||
| import com.jayway.jsonpath.DocumentContext; | import com.jayway.jsonpath.DocumentContext; | ||||||
| import com.jayway.jsonpath.JsonPath; | import com.jayway.jsonpath.JsonPath; | ||||||
| import com.jayway.jsonpath.Option; | import com.jayway.jsonpath.Option; | ||||||
|  | import com.jayway.jsonpath.Filter; | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import java.io.InputStream; | import java.io.InputStream; | ||||||
| @ -98,4 +100,14 @@ public class ServiceIntegrationTest { | |||||||
| 
 | 
 | ||||||
|         assertEquals("Spectre", title); |         assertEquals("Spectre", title); | ||||||
|     } |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenJsonPathWithFilterPredicate_whenReadingRootNode_thenCorrect() { | ||||||
|  |         Filter expensiveFilter = Filter.filter(Criteria.where("director") | ||||||
|  |             .contains("Sam Mendes")); | ||||||
|  |         List<Map<String, Object>> predicate = JsonPath.parse(jsonString) | ||||||
|  |             .read("$[?]['director']", expensiveFilter); | ||||||
|  |         assertEquals(predicate.size(), 2); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
| } | } | ||||||
| @ -65,4 +65,4 @@ | |||||||
|         <maven-jar-plugin.version>3.0.2</maven-jar-plugin.version> |         <maven-jar-plugin.version>3.0.2</maven-jar-plugin.version> | ||||||
|     </properties> |     </properties> | ||||||
| 
 | 
 | ||||||
| </project> | </project> | ||||||
|  | |||||||
| @ -11,4 +11,5 @@ This module contains articles about Project Lombok. | |||||||
| - [Jackson’s Deserialization With Lombok](https://www.baeldung.com/java-jackson-deserialization-lombok) | - [Jackson’s Deserialization With Lombok](https://www.baeldung.com/java-jackson-deserialization-lombok) | ||||||
| - [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) | - [Constructor Injection in Spring with Lombok](https://www.baeldung.com/spring-injection-lombok) | ||||||
| - [@StandardException Annotation in Lombok](https://www.baeldung.com/lombok-standardexception-annotation) | - [@StandardException Annotation in Lombok](https://www.baeldung.com/lombok-standardexception-annotation) | ||||||
|  | - [Lombok EqualsAndHashCode Annotation](https://www.baeldung.com/java-lombok-equalsandhashcode) | ||||||
| - More articles: [[<-- prev]](../lombok) | - More articles: [[<-- prev]](../lombok) | ||||||
|  | |||||||
| @ -19,6 +19,7 @@ | |||||||
|             <artifactId>junit</artifactId> |             <artifactId>junit</artifactId> | ||||||
|             <scope>test</scope> |             <scope>test</scope> | ||||||
|         </dependency> |         </dependency> | ||||||
|  | 
 | ||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
|     <build> |     <build> | ||||||
| @ -37,14 +38,15 @@ | |||||||
|                         </property> |                         </property> | ||||||
|                     </properties> |                     </properties> | ||||||
|                 </configuration> |                 </configuration> | ||||||
|                 <dependencies> |                 <!-- Activate this for understanding the article only --> | ||||||
|  |                 <!-- <dependencies> | ||||||
|                     <dependency> |                     <dependency> | ||||||
|                         <!-- Deactivate JUnit 4.7 engine by overriding it with an empty dummy --> |                         Deactivate JUnit 4.7 engine by overriding it with an empty dummy | ||||||
|                         <groupId>org.apache.maven.surefire</groupId> |                         <groupId>org.apache.maven.surefire</groupId> | ||||||
|                         <artifactId>surefire-junit47</artifactId> |                         <artifactId>surefire-junit47</artifactId> | ||||||
|                         <version>dummy</version> |                         <version>dummy</version> | ||||||
|                     </dependency> |                     </dependency> | ||||||
|                 </dependencies> |                 </dependencies> --> | ||||||
|             </plugin> |             </plugin> | ||||||
|         </plugins> |         </plugins> | ||||||
|     </build> |     </build> | ||||||
|  | |||||||
| @ -6,4 +6,10 @@ | |||||||
|     <groupId>org.apache.maven.surefire</groupId> |     <groupId>org.apache.maven.surefire</groupId> | ||||||
|     <artifactId>surefire-junit47</artifactId> |     <artifactId>surefire-junit47</artifactId> | ||||||
|     <version>dummy</version> |     <version>dummy</version> | ||||||
|  | 
 | ||||||
|  |     <parent> | ||||||
|  |         <groupId>com.baeldung.dependency-exclusion</groupId> | ||||||
|  |         <artifactId>dependency-exclusion</artifactId> | ||||||
|  |         <version>0.0.1-SNAPSHOT</version> | ||||||
|  |     </parent> | ||||||
| </project> | </project> | ||||||
|  | |||||||
| @ -94,7 +94,7 @@ | |||||||
|         <rest-assured.version>3.3.0</rest-assured.version> |         <rest-assured.version>3.3.0</rest-assured.version> | ||||||
|         <!-- plugins --> |         <!-- plugins --> | ||||||
|         <thin.version>1.0.22.RELEASE</thin.version> |         <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> |         <aspectjweaver.version>1.9.1</aspectjweaver.version> | ||||||
|         <mysql-connector-java.version>8.0.31</mysql-connector-java.version> |         <mysql-connector-java.version>8.0.31</mysql-connector-java.version> | ||||||
|     </properties> |     </properties> | ||||||
|  | |||||||
| @ -28,12 +28,12 @@ | |||||||
|         <dependency> |         <dependency> | ||||||
|             <groupId>com.itextpdf</groupId> |             <groupId>com.itextpdf</groupId> | ||||||
|             <artifactId>itextpdf</artifactId> |             <artifactId>itextpdf</artifactId> | ||||||
|             <version>5.5.13.3</version> |             <version>${itextpdf.version}</version> | ||||||
|         </dependency> |         </dependency> | ||||||
|         <dependency> |         <dependency> | ||||||
|             <groupId>org.apache.pdfbox</groupId> |             <groupId>org.apache.pdfbox</groupId> | ||||||
|             <artifactId>pdfbox</artifactId> |             <artifactId>pdfbox</artifactId> | ||||||
|             <version>3.0.0-RC1</version> |             <version>${pdfbox.version}</version> | ||||||
|         </dependency> |         </dependency> | ||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
| @ -48,8 +48,10 @@ | |||||||
|     </build> |     </build> | ||||||
| 
 | 
 | ||||||
|     <properties> |     <properties> | ||||||
|  |         <itextpdf.version>5.5.13.3</itextpdf.version> | ||||||
|         <itextpdf.core.version>7.2.3</itextpdf.core.version> |         <itextpdf.core.version>7.2.3</itextpdf.core.version> | ||||||
|         <itextpdf.cleanup.version>3.0.1</itextpdf.cleanup.version> |         <itextpdf.cleanup.version>3.0.1</itextpdf.cleanup.version> | ||||||
|  |         <pdfbox.version>3.0.0-RC1</pdfbox.version> | ||||||
|     </properties> |     </properties> | ||||||
| 
 | 
 | ||||||
| </project> | </project> | ||||||
| @ -106,7 +106,7 @@ | |||||||
|     <properties> |     <properties> | ||||||
|         <pdfbox-tools.version>2.0.25</pdfbox-tools.version> |         <pdfbox-tools.version>2.0.25</pdfbox-tools.version> | ||||||
|         <pdf2dom.version>2.0.1</pdf2dom.version> |         <pdf2dom.version>2.0.1</pdf2dom.version> | ||||||
|         <itextpdf.version>5.5.10</itextpdf.version> |         <itextpdf.version>5.5.13.3</itextpdf.version> | ||||||
|         <xmlworker.version>5.5.10</xmlworker.version> |         <xmlworker.version>5.5.10</xmlworker.version> | ||||||
|         <poi-scratchpad.version>3.15</poi-scratchpad.version> |         <poi-scratchpad.version>3.15</poi-scratchpad.version> | ||||||
|         <batik-transcoder.version>1.8</batik-transcoder.version> |         <batik-transcoder.version>1.8</batik-transcoder.version> | ||||||
|  | |||||||
| @ -76,13 +76,18 @@ | |||||||
|             <version>${org.springframework.version}</version> |             <version>${org.springframework.version}</version> | ||||||
|             <scope>test</scope> |             <scope>test</scope> | ||||||
|         </dependency> |         </dependency> | ||||||
|  |         <dependency> | ||||||
|  |             <groupId>io.hypersistence</groupId> | ||||||
|  |             <artifactId>hypersistence-utils-hibernate-60</artifactId> | ||||||
|  |             <version>3.3.1</version> | ||||||
|  |         </dependency> | ||||||
|     </dependencies> |     </dependencies> | ||||||
| 
 | 
 | ||||||
|     <properties> |     <properties> | ||||||
|         <!-- Spring --> |         <!-- Spring --> | ||||||
|         <org.springframework.version>5.0.2.RELEASE</org.springframework.version> |         <org.springframework.version>6.0.6</org.springframework.version> | ||||||
|         <org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version> |         <org.springframework.data.version>3.0.3</org.springframework.data.version> | ||||||
|         <hibernate-core.version>5.6.7.Final</hibernate-core.version> |         <hibernate-core.version>6.1.7.Final</hibernate-core.version> | ||||||
|         <maven.deploy.skip>true</maven.deploy.skip> |         <maven.deploy.skip>true</maven.deploy.skip> | ||||||
|         <tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version> |         <tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version> | ||||||
|     </properties> |     </properties> | ||||||
|  | |||||||
| @ -2,9 +2,9 @@ package com.baeldung.hibernate.creationupdatetimestamp.model; | |||||||
| 
 | 
 | ||||||
| import java.time.Instant; | import java.time.Instant; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.annotations.CreationTimestamp; | import org.hibernate.annotations.CreationTimestamp; | ||||||
| import org.hibernate.annotations.UpdateTimestamp; | import org.hibernate.annotations.UpdateTimestamp; | ||||||
|  | |||||||
| @ -1,11 +1,11 @@ | |||||||
| package com.baeldung.hibernate.customtypes; | package com.baeldung.hibernate.customtypes; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.HibernateException; | import org.hibernate.HibernateException; | ||||||
|  | import org.hibernate.engine.spi.SessionFactoryImplementor; | ||||||
| import org.hibernate.engine.spi.SharedSessionContractImplementor; | import org.hibernate.engine.spi.SharedSessionContractImplementor; | ||||||
| import org.hibernate.type.IntegerType; | import org.hibernate.metamodel.spi.ValueAccess; | ||||||
| import org.hibernate.type.StringType; |  | ||||||
| import org.hibernate.type.Type; |  | ||||||
| import org.hibernate.usertype.CompositeUserType; | import org.hibernate.usertype.CompositeUserType; | ||||||
|  | import org.hibernate.usertype.UserType; | ||||||
| 
 | 
 | ||||||
| import java.io.Serializable; | import java.io.Serializable; | ||||||
| import java.sql.PreparedStatement; | import java.sql.PreparedStatement; | ||||||
| @ -14,74 +14,51 @@ import java.sql.SQLException; | |||||||
| import java.sql.Types; | import java.sql.Types; | ||||||
| import java.util.Objects; | import java.util.Objects; | ||||||
| 
 | 
 | ||||||
| public class AddressType implements CompositeUserType { | public class AddressType implements CompositeUserType<Address>, UserType<Address> { | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public String[] getPropertyNames() { |     public Object getPropertyValue(Address component, int property) throws HibernateException { | ||||||
|         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; |  | ||||||
| 
 | 
 | ||||||
|         switch (property) { |         switch (property) { | ||||||
|             case 0: |             case 0: | ||||||
|                 return empAdd.getAddressLine1(); |                 return component.getAddressLine1(); | ||||||
|             case 1: |             case 1: | ||||||
|                 return empAdd.getAddressLine2(); |                 return component.getAddressLine2(); | ||||||
|             case 2: |             case 2: | ||||||
|                 return empAdd.getCity(); |                 return component.getCity(); | ||||||
|             case 3: |             case 3: | ||||||
|                 return empAdd.getCountry(); |                 return component.getCountry(); | ||||||
|             case 4: |             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()); | ||||||
|         } |         } | ||||||
| 
 |  | ||||||
|         throw new IllegalArgumentException(property + |  | ||||||
|                 " is an invalid property index for class type " + |  | ||||||
|                 component.getClass().getName()); |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public void setPropertyValue(Object component, int property, Object value) throws HibernateException { |     public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { | ||||||
| 
 |         return null; | ||||||
|         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 |     @Override | ||||||
|     public Class returnedClass() { |     public Class<?> embeddable() { | ||||||
|         return Address.class; |         return Address.class; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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) |         if (x == y) | ||||||
|             return true; |             return true; | ||||||
| 
 | 
 | ||||||
| @ -92,57 +69,52 @@ public class AddressType implements CompositeUserType { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public int hashCode(Object x) throws HibernateException { |     public int hashCode(Address x) { | ||||||
|         return x.hashCode(); |         return x.hashCode(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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(); |         Address empAdd = new Address(); | ||||||
|         empAdd.setAddressLine1(rs.getString(names[0])); |         empAdd.setAddressLine1(rs.getString(position)); | ||||||
| 
 | 
 | ||||||
|         if (rs.wasNull()) |         if (rs.wasNull()) | ||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         empAdd.setAddressLine2(rs.getString(names[1])); |         empAdd.setAddressLine2(rs.getString(position)); | ||||||
|         empAdd.setCity(rs.getString(names[2])); |         empAdd.setCity(rs.getString(position)); | ||||||
|         empAdd.setCountry(rs.getString(names[3])); |         empAdd.setCountry(rs.getString(position)); | ||||||
|         empAdd.setZipCode(rs.getInt(names[4])); |         empAdd.setZipCode(rs.getInt(position)); | ||||||
| 
 | 
 | ||||||
|         return empAdd; |         return empAdd; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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)) |         if (Objects.isNull(value)) | ||||||
|             st.setNull(index, Types.VARCHAR); |             st.setNull(index, Types.VARCHAR); | ||||||
|         else { |         else { | ||||||
| 
 | 
 | ||||||
|             Address empAdd = (Address) value; |             st.setString(index, value.getAddressLine1()); | ||||||
|             st.setString(index, empAdd.getAddressLine1()); |             st.setString(index + 1, value.getAddressLine2()); | ||||||
|             st.setString(index + 1, empAdd.getAddressLine2()); |             st.setString(index + 2, value.getCity()); | ||||||
|             st.setString(index + 2, empAdd.getCity()); |             st.setString(index + 3, value.getCountry()); | ||||||
|             st.setString(index + 3, empAdd.getCountry()); |             st.setInt(index + 4, value.getZipCode()); | ||||||
|             st.setInt(index + 4, empAdd.getZipCode()); |  | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object deepCopy(Object value) throws HibernateException { |     public Address deepCopy(Address value) { | ||||||
| 
 |  | ||||||
|         if (Objects.isNull(value)) |         if (Objects.isNull(value)) | ||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         Address oldEmpAdd = (Address) value; |  | ||||||
|         Address newEmpAdd = new Address(); |         Address newEmpAdd = new Address(); | ||||||
| 
 | 
 | ||||||
|         newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1()); |         newEmpAdd.setAddressLine1(value.getAddressLine1()); | ||||||
|         newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2()); |         newEmpAdd.setAddressLine2(value.getAddressLine2()); | ||||||
|         newEmpAdd.setCity(oldEmpAdd.getCity()); |         newEmpAdd.setCity(value.getCity()); | ||||||
|         newEmpAdd.setCountry(oldEmpAdd.getCountry()); |         newEmpAdd.setCountry(value.getCountry()); | ||||||
|         newEmpAdd.setZipCode(oldEmpAdd.getZipCode()); |         newEmpAdd.setZipCode(value.getZipCode()); | ||||||
| 
 | 
 | ||||||
|         return newEmpAdd; |         return newEmpAdd; | ||||||
|     } |     } | ||||||
| @ -153,17 +125,27 @@ public class AddressType implements CompositeUserType { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { |     public Serializable disassemble(Address value) { | ||||||
|         return (Serializable) deepCopy(value); |         return (Serializable) deepCopy(value); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { |     public Address assemble(Serializable cached, Object owner) { | ||||||
|         return deepCopy(cached); |         return deepCopy((Address) cached); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { |     public Address replace(Address detached, Address managed, Object owner) { | ||||||
|         return original; |         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); | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,14 +1,14 @@ | |||||||
| package com.baeldung.hibernate.customtypes; | package com.baeldung.hibernate.customtypes; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.type.LocalDateType; |  | ||||||
| import org.hibernate.type.descriptor.WrapperOptions; | 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.ImmutableMutabilityPlan; | ||||||
| import org.hibernate.type.descriptor.java.MutabilityPlan; |  | ||||||
| 
 | 
 | ||||||
| import java.time.LocalDate; | 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(); |     public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor(); | ||||||
| 
 | 
 | ||||||
| @ -18,12 +18,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD | |||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public String toString(LocalDate value) { |     public String toString(LocalDate value) { | ||||||
|         return LocalDateType.FORMATTER.format(value); |         return DateTimeFormatter.ISO_LOCAL_DATE.format(value); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public LocalDate fromString(String string) { |     public LocalDate fromString(CharSequence string) { | ||||||
|         return LocalDate.from(LocalDateType.FORMATTER.parse(string)); |         return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse(string)); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
| @ -33,7 +33,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD | |||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         if (String.class.isAssignableFrom(type)) |         if (String.class.isAssignableFrom(type)) | ||||||
|             return (X) LocalDateType.FORMATTER.format(value); |             return (X) DateTimeFormatter.ISO_LOCAL_DATE.format(value); | ||||||
| 
 | 
 | ||||||
|         throw unknownUnwrap(type); |         throw unknownUnwrap(type); | ||||||
|     } |     } | ||||||
| @ -44,7 +44,7 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor<LocalD | |||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         if(String.class.isInstance(value)) |         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()); |         throw unknownWrap(value.getClass()); | ||||||
|     } |     } | ||||||
|  | |||||||
| @ -2,18 +2,16 @@ package com.baeldung.hibernate.customtypes; | |||||||
| 
 | 
 | ||||||
| import org.hibernate.dialect.Dialect; | import org.hibernate.dialect.Dialect; | ||||||
| import org.hibernate.type.AbstractSingleColumnStandardBasicType; | import org.hibernate.type.AbstractSingleColumnStandardBasicType; | ||||||
| import org.hibernate.type.DiscriminatorType; | import org.hibernate.type.descriptor.jdbc.VarcharJdbcType; | ||||||
| import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor; |  | ||||||
| import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; |  | ||||||
| 
 | 
 | ||||||
| import java.time.LocalDate; | 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 static final LocalDateStringType INSTANCE = new LocalDateStringType(); | ||||||
| 
 | 
 | ||||||
|     public LocalDateStringType() { |     public LocalDateStringType() { | ||||||
|         super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); |         super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
| @ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicType<L | |||||||
|         return "LocalDateString"; |         return "LocalDateString"; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     public LocalDate stringToObject(String xml) { | ||||||
|     public LocalDate stringToObject(String xml) throws Exception { |  | ||||||
|         return fromString(xml); |         return fromString(xml); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     public String objectToSQLString(LocalDate value, Dialect dialect) { | ||||||
|     public String objectToSQLString(LocalDate value, Dialect dialect) throws Exception { |         return '\'' + LocalDateStringJavaDescriptor.INSTANCE.toString(value) + '\''; | ||||||
|         return '\'' + toString(value) + '\''; |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,20 +1,19 @@ | |||||||
| package com.baeldung.hibernate.customtypes; | package com.baeldung.hibernate.customtypes; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.annotations.Columns; | import org.hibernate.annotations.CompositeType; | ||||||
| import org.hibernate.annotations.Parameter; | import org.hibernate.annotations.Parameter; | ||||||
| import org.hibernate.annotations.Type; | import org.hibernate.annotations.Type; | ||||||
| import org.hibernate.annotations.TypeDef; | import org.hibernate.usertype.UserTypeLegacyBridge; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.AttributeOverride; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.AttributeOverrides; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.GeneratedValue; | ||||||
|  | import jakarta.persistence.Id; | ||||||
|  | import jakarta.persistence.Table; | ||||||
| import java.time.LocalDate; | import java.time.LocalDate; | ||||||
| 
 | 
 | ||||||
| @TypeDef(name = "PhoneNumber", |  | ||||||
|         typeClass = PhoneNumberType.class, |  | ||||||
|         defaultForType = PhoneNumber.class) |  | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "OfficeEmployee") | @Table(name = "OfficeEmployee") | ||||||
| public class OfficeEmployee { | public class OfficeEmployee { | ||||||
| @ -24,25 +23,36 @@ public class OfficeEmployee { | |||||||
|     private long id; |     private long id; | ||||||
| 
 | 
 | ||||||
|     @Column |     @Column | ||||||
|     @Type(type = "LocalDateString") |     @Type( | ||||||
|  |             value = UserTypeLegacyBridge.class, | ||||||
|  |             parameters = @Parameter(name = UserTypeLegacyBridge.TYPE_NAME_PARAM_KEY, value = "LocalDateString") | ||||||
|  |     ) | ||||||
|     private LocalDate dateOfJoining; |     private LocalDate dateOfJoining; | ||||||
| 
 | 
 | ||||||
|     @Columns(columns = {@Column(name = "country_code"), |     @AttributeOverrides({ | ||||||
|             @Column(name = "city_code"), |             @AttributeOverride(name = "countryCode", column = @Column(name = "country_code")), | ||||||
|             @Column(name = "number")}) |             @AttributeOverride(name = "cityCode", column = @Column(name = "city_code")), | ||||||
|  |             @AttributeOverride(name = "number", column = @Column(name = "number")) | ||||||
|  |     }) | ||||||
|  |     @Type(value = PhoneNumberType.class) | ||||||
|     private PhoneNumber employeeNumber; |     private PhoneNumber employeeNumber; | ||||||
| 
 | 
 | ||||||
|     @Columns(columns = {@Column(name = "address_line_1"), |     @CompositeType(value = com.baeldung.hibernate.customtypes.AddressType.class) | ||||||
|             @Column(name = "address_line_2"), |     @AttributeOverrides({ | ||||||
|             @Column(name = "city"), @Column(name = "country"), |             @AttributeOverride(name = "addressLine1", column = @Column(name = "address_line_1")), | ||||||
|             @Column(name = "zip_code")}) |             @AttributeOverride(name = "addressLine2", column = @Column(name = "address_line_2")), | ||||||
|     @Type(type = "com.baeldung.hibernate.customtypes.AddressType") |             @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; |     private Address empAddress; | ||||||
| 
 | 
 | ||||||
|     @Type(type = "com.baeldung.hibernate.customtypes.SalaryType", |     @Type(value = com.baeldung.hibernate.customtypes.SalaryType.class, | ||||||
|             parameters = {@Parameter(name = "currency", value = "USD")}) |             parameters = {@Parameter(name = "currency", value = "USD")}) | ||||||
|     @Columns(columns = {@Column(name = "amount"), |    @AttributeOverrides({ | ||||||
|             @Column(name = "currency")}) |             @AttributeOverride(name = "amount", column = @Column(name = "amount")), | ||||||
|  |             @AttributeOverride(name = "currency", column = @Column(name = "currency")) | ||||||
|  |     }) | ||||||
|     private Salary salary; |     private Salary salary; | ||||||
| 
 | 
 | ||||||
|     public Salary getSalary() { |     public Salary getSalary() { | ||||||
|  | |||||||
| @ -2,11 +2,11 @@ package com.baeldung.hibernate.customtypes; | |||||||
| 
 | 
 | ||||||
| import java.util.Objects; | import java.util.Objects; | ||||||
| 
 | 
 | ||||||
| public final class PhoneNumber { | public class PhoneNumber { | ||||||
| 
 | 
 | ||||||
|     private final int countryCode; |     private int countryCode; | ||||||
|     private final int cityCode; |     private int cityCode; | ||||||
|     private final int number; |     private int number; | ||||||
| 
 | 
 | ||||||
|     public PhoneNumber(int countryCode, int cityCode, int number) { |     public PhoneNumber(int countryCode, int cityCode, int number) { | ||||||
|         this.countryCode = countryCode; |         this.countryCode = countryCode; | ||||||
|  | |||||||
| @ -1,6 +1,5 @@ | |||||||
| package com.baeldung.hibernate.customtypes; | package com.baeldung.hibernate.customtypes; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.HibernateException; |  | ||||||
| import org.hibernate.engine.spi.SharedSessionContractImplementor; | import org.hibernate.engine.spi.SharedSessionContractImplementor; | ||||||
| import org.hibernate.usertype.UserType; | import org.hibernate.usertype.UserType; | ||||||
| 
 | 
 | ||||||
| @ -11,11 +10,11 @@ import java.sql.SQLException; | |||||||
| import java.sql.Types; | import java.sql.Types; | ||||||
| import java.util.Objects; | import java.util.Objects; | ||||||
| 
 | 
 | ||||||
|  | public class PhoneNumberType implements UserType<PhoneNumber> { | ||||||
| 
 | 
 | ||||||
| public class PhoneNumberType implements UserType { |  | ||||||
|     @Override |     @Override | ||||||
|     public int[] sqlTypes() { |     public int getSqlType() { | ||||||
|         return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER}; |         return Types.INTEGER; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
| @ -24,7 +23,7 @@ public class PhoneNumberType implements UserType { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public boolean equals(Object x, Object y) throws HibernateException { |     public boolean equals(PhoneNumber x, PhoneNumber y) { | ||||||
|         if (x == y) |         if (x == y) | ||||||
|             return true; |             return true; | ||||||
|         if (Objects.isNull(x) || Objects.isNull(y)) |         if (Objects.isNull(x) || Objects.isNull(y)) | ||||||
| @ -34,48 +33,42 @@ public class PhoneNumberType implements UserType { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public int hashCode(Object x) throws HibernateException { |     public int hashCode(PhoneNumber x) { | ||||||
|         return x.hashCode(); |         return x.hashCode(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { |     public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException { | ||||||
|         int countryCode = rs.getInt(names[0]); |         int countryCode = rs.getInt(position); | ||||||
| 
 | 
 | ||||||
|         if (rs.wasNull()) |         if (rs.wasNull()) | ||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         int cityCode = rs.getInt(names[1]); |         int cityCode = rs.getInt(position); | ||||||
|         int number = rs.getInt(names[2]); |         int number = rs.getInt(position); | ||||||
|         PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number); |  | ||||||
| 
 | 
 | ||||||
|         return employeeNumber; |         return new PhoneNumber(countryCode, cityCode, number); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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)) { |         if (Objects.isNull(value)) { | ||||||
|             st.setNull(index, Types.INTEGER); |             st.setNull(index, Types.INTEGER); | ||||||
|             st.setNull(index+1, Types.INTEGER); |             st.setNull(index+1, Types.INTEGER); | ||||||
|             st.setNull(index+2, Types.INTEGER); |             st.setNull(index+2, Types.INTEGER); | ||||||
|         } else { |         } else { | ||||||
|             PhoneNumber employeeNumber = (PhoneNumber) value; |             st.setInt(index, value.getCountryCode()); | ||||||
|             st.setInt(index,employeeNumber.getCountryCode()); |             st.setInt(index+1, value.getCityCode()); | ||||||
|             st.setInt(index+1,employeeNumber.getCityCode()); |             st.setInt(index+2, value.getNumber()); | ||||||
|             st.setInt(index+2,employeeNumber.getNumber()); |  | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object deepCopy(Object value) throws HibernateException { |     public PhoneNumber deepCopy(PhoneNumber value) { | ||||||
|         if (Objects.isNull(value)) |         if (Objects.isNull(value)) | ||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         PhoneNumber empNumber = (PhoneNumber) value; |         return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber()); | ||||||
|         PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber()); |  | ||||||
| 
 |  | ||||||
|         return newEmpNumber; |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
| @ -84,17 +77,17 @@ public class PhoneNumberType implements UserType { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Serializable disassemble(Object value) throws HibernateException { |     public Serializable disassemble(PhoneNumber value) { | ||||||
|         return (Serializable) value; |         return (Serializable) value; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object assemble(Serializable cached, Object owner) throws HibernateException { |     public PhoneNumber assemble(Serializable cached, Object owner) { | ||||||
|         return cached; |         return (PhoneNumber) cached; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object replace(Object original, Object target, Object owner) throws HibernateException { |     public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) { | ||||||
|         return original; |         return detached; | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  | |||||||
| @ -1,12 +1,12 @@ | |||||||
| package com.baeldung.hibernate.customtypes; | package com.baeldung.hibernate.customtypes; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.HibernateException; | import org.hibernate.HibernateException; | ||||||
|  | import org.hibernate.engine.spi.SessionFactoryImplementor; | ||||||
| import org.hibernate.engine.spi.SharedSessionContractImplementor; | import org.hibernate.engine.spi.SharedSessionContractImplementor; | ||||||
| import org.hibernate.type.LongType; | import org.hibernate.metamodel.spi.ValueAccess; | ||||||
| import org.hibernate.type.StringType; |  | ||||||
| import org.hibernate.type.Type; |  | ||||||
| import org.hibernate.usertype.CompositeUserType; | import org.hibernate.usertype.CompositeUserType; | ||||||
| import org.hibernate.usertype.DynamicParameterizedType; | import org.hibernate.usertype.DynamicParameterizedType; | ||||||
|  | import org.hibernate.usertype.UserType; | ||||||
| 
 | 
 | ||||||
| import java.io.Serializable; | import java.io.Serializable; | ||||||
| import java.sql.PreparedStatement; | import java.sql.PreparedStatement; | ||||||
| @ -16,65 +16,47 @@ import java.sql.Types; | |||||||
| import java.util.Objects; | import java.util.Objects; | ||||||
| import java.util.Properties; | import java.util.Properties; | ||||||
| 
 | 
 | ||||||
| public class SalaryType implements CompositeUserType, DynamicParameterizedType { | public class SalaryType implements UserType<Salary>, CompositeUserType<Salary>, DynamicParameterizedType { | ||||||
| 
 | 
 | ||||||
|     private String localCurrency; |     private String localCurrency; | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public String[] getPropertyNames() { |     public Object getPropertyValue(Salary component, int property) throws HibernateException { | ||||||
|         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; |  | ||||||
| 
 | 
 | ||||||
|         switch (property) { |         switch (property) { | ||||||
|             case 0: |             case 0: | ||||||
|                 return salary.getAmount(); |                 return component.getAmount(); | ||||||
|             case 1: |             case 1: | ||||||
|                 return salary.getCurrency(); |                 return component.getCurrency(); | ||||||
|  |             default: | ||||||
|  |                 throw new IllegalArgumentException(property + | ||||||
|  |                         " is an invalid property index for class type " + | ||||||
|  |                         component.getClass().getName()); | ||||||
|         } |         } | ||||||
| 
 |  | ||||||
|         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 |     @Override | ||||||
|     public Class returnedClass() { |     public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) { | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Override | ||||||
|  |     public Class<?> embeddable() { | ||||||
|         return Salary.class; |         return Salary.class; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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) |         if (x == y) | ||||||
|             return true; |             return true; | ||||||
| 
 | 
 | ||||||
| @ -82,54 +64,48 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType { | |||||||
|             return false; |             return false; | ||||||
| 
 | 
 | ||||||
|         return x.equals(y); |         return x.equals(y); | ||||||
| 
 |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public int hashCode(Object x) throws HibernateException { |     public int hashCode(Salary x) { | ||||||
|         return x.hashCode(); |         return x.hashCode(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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 salary = new Salary(); | ||||||
|         salary.setAmount(rs.getLong(names[0])); |         salary.setAmount(rs.getLong(position)); | ||||||
| 
 | 
 | ||||||
|         if (rs.wasNull()) |         if (rs.wasNull()) | ||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         salary.setCurrency(rs.getString(names[1])); |         salary.setCurrency(rs.getString(position)); | ||||||
| 
 | 
 | ||||||
|         return salary; |         return salary; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @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)) |         if (Objects.isNull(value)) | ||||||
|             st.setNull(index, Types.BIGINT); |             st.setNull(index, Types.BIGINT); | ||||||
|         else { |         else { | ||||||
| 
 | 
 | ||||||
|             Salary salary = (Salary) value; |             st.setLong(index, SalaryCurrencyConvertor.convert( | ||||||
|             st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(), |                     value.getAmount(), | ||||||
|                     salary.getCurrency(), localCurrency)); |                     value.getCurrency(), localCurrency)); | ||||||
|             st.setString(index + 1, salary.getCurrency()); |             st.setString(index + 1, value.getCurrency()); | ||||||
|         } |         } | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object deepCopy(Object value) throws HibernateException { |     public Salary deepCopy(Salary value) { | ||||||
| 
 |  | ||||||
|         if (Objects.isNull(value)) |         if (Objects.isNull(value)) | ||||||
|             return null; |             return null; | ||||||
| 
 | 
 | ||||||
|         Salary oldSal = (Salary) value; |  | ||||||
|         Salary newSal = new Salary(); |         Salary newSal = new Salary(); | ||||||
| 
 | 
 | ||||||
|         newSal.setAmount(oldSal.getAmount()); |         newSal.setAmount(value.getAmount()); | ||||||
|         newSal.setCurrency(oldSal.getCurrency()); |         newSal.setCurrency(value.getCurrency()); | ||||||
| 
 | 
 | ||||||
|         return newSal; |         return newSal; | ||||||
|     } |     } | ||||||
| @ -140,18 +116,18 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { |     public Serializable disassemble(Salary value) { | ||||||
|         return (Serializable) deepCopy(value); |         return (Serializable) deepCopy(value); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException { |     public Salary assemble(Serializable cached, Object owner) { | ||||||
|         return deepCopy(cached); |         return deepCopy((Salary) cached); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|     public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException { |     public Salary replace(Salary detached, Salary managed, Object owner) { | ||||||
|         return original; |         return detached; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Override |     @Override | ||||||
|  | |||||||
| @ -4,7 +4,7 @@ import org.hibernate.annotations.Cascade; | |||||||
| import org.hibernate.annotations.CascadeType; | import org.hibernate.annotations.CascadeType; | ||||||
| import org.hibernate.annotations.Immutable; | import org.hibernate.annotations.Immutable; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.*; | import jakarta.persistence.*; | ||||||
| import java.util.Set; | import java.util.Set; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
|  | |||||||
| @ -3,7 +3,7 @@ package com.baeldung.hibernate.immutable.entities; | |||||||
| import org.hibernate.annotations.GenericGenerator; | import org.hibernate.annotations.GenericGenerator; | ||||||
| import org.hibernate.annotations.Immutable; | import org.hibernate.annotations.Immutable; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.*; | import jakarta.persistence.*; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Immutable | @Immutable | ||||||
|  | |||||||
| @ -1,12 +1,12 @@ | |||||||
| package com.baeldung.hibernate.joincolumn; | package com.baeldung.hibernate.joincolumn; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.FetchType; | import jakarta.persistence.FetchType; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.JoinColumn; | import jakarta.persistence.JoinColumn; | ||||||
| import javax.persistence.ManyToOne; | import jakarta.persistence.ManyToOne; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class Email { | public class Email { | ||||||
|  | |||||||
| @ -1,13 +1,13 @@ | |||||||
| package com.baeldung.hibernate.joincolumn; | package com.baeldung.hibernate.joincolumn; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.FetchType; | import jakarta.persistence.FetchType; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.JoinColumn; | import jakarta.persistence.JoinColumn; | ||||||
| import javax.persistence.JoinColumns; | import jakarta.persistence.JoinColumns; | ||||||
| import javax.persistence.ManyToOne; | import jakarta.persistence.ManyToOne; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class Office { | public class Office { | ||||||
|  | |||||||
| @ -1,10 +1,10 @@ | |||||||
| package com.baeldung.hibernate.joincolumn; | package com.baeldung.hibernate.joincolumn; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class OfficeAddress { | public class OfficeAddress { | ||||||
|  | |||||||
| @ -1,12 +1,12 @@ | |||||||
| package com.baeldung.hibernate.joincolumn; | package com.baeldung.hibernate.joincolumn; | ||||||
| 
 | 
 | ||||||
| import java.util.List; | import java.util.List; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.FetchType; | import jakarta.persistence.FetchType; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.OneToMany; | import jakarta.persistence.OneToMany; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class OfficialEmployee { | public class OfficialEmployee { | ||||||
|  | |||||||
| @ -3,12 +3,12 @@ package com.baeldung.hibernate.lazycollection.model; | |||||||
| import org.hibernate.annotations.LazyCollection; | import org.hibernate.annotations.LazyCollection; | ||||||
| import org.hibernate.annotations.LazyCollectionOption; | import org.hibernate.annotations.LazyCollectionOption; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.OrderColumn; | import jakarta.persistence.OrderColumn; | ||||||
| import javax.persistence.OneToMany; | import jakarta.persistence.OneToMany; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||||
| import java.util.List; | import java.util.List; | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -1,11 +1,10 @@ | |||||||
| package com.baeldung.hibernate.lazycollection.model; | package com.baeldung.hibernate.lazycollection.model; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.OrderColumn; | import jakarta.persistence.ManyToOne; | ||||||
| import javax.persistence.ManyToOne; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.Entity; |  | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class Employee { | public class Employee { | ||||||
|  | |||||||
| @ -43,8 +43,8 @@ public class HibernateAnnotationUtil { | |||||||
|         return metadata.buildSessionFactory(); |         return metadata.buildSessionFactory(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private static Map<String, String> dbSettings() { |     private static Map<String, Object> dbSettings() { | ||||||
|         Map<String, String> dbSettings = new HashMap<>(); |         Map<String, Object> dbSettings = new HashMap<>(); | ||||||
|         dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many"); |         dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many"); | ||||||
|         dbSettings.put(Environment.USER, "sa"); |         dbSettings.put(Environment.USER, "sa"); | ||||||
|         dbSettings.put(Environment.PASS, ""); |         dbSettings.put(Environment.PASS, ""); | ||||||
|  | |||||||
| @ -2,13 +2,13 @@ package com.baeldung.hibernate.oneToMany.model; | |||||||
| 
 | 
 | ||||||
| import java.util.Set; | import java.util.Set; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.OneToMany; | import jakarta.persistence.OneToMany; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "CART") | @Table(name = "CART") | ||||||
|  | |||||||
| @ -1,13 +1,13 @@ | |||||||
| package com.baeldung.hibernate.oneToMany.model; | package com.baeldung.hibernate.oneToMany.model; | ||||||
| 
 | 
 | ||||||
| import java.util.Set; | import java.util.Set; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.JoinColumn; | import jakarta.persistence.JoinColumn; | ||||||
| import javax.persistence.OneToMany; | import jakarta.persistence.OneToMany; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "CARTOIO") | @Table(name = "CARTOIO") | ||||||
|  | |||||||
| @ -1,13 +1,13 @@ | |||||||
| package com.baeldung.hibernate.oneToMany.model; | package com.baeldung.hibernate.oneToMany.model; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.JoinColumn; | import jakarta.persistence.JoinColumn; | ||||||
| import javax.persistence.ManyToOne; | import jakarta.persistence.ManyToOne; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "ITEMS") | @Table(name = "ITEMS") | ||||||
|  | |||||||
| @ -1,12 +1,12 @@ | |||||||
| package com.baeldung.hibernate.oneToMany.model; | package com.baeldung.hibernate.oneToMany.model; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.JoinColumn; | import jakarta.persistence.JoinColumn; | ||||||
| import javax.persistence.ManyToOne; | import jakarta.persistence.ManyToOne; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "ITEMSOIO") | @Table(name = "ITEMSOIO") | ||||||
|  | |||||||
| @ -1,9 +1,9 @@ | |||||||
| package com.baeldung.hibernate.pojo; | package com.baeldung.hibernate.pojo; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import java.io.Serializable; | import java.io.Serializable; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
|  | |||||||
| @ -3,10 +3,10 @@ package com.baeldung.hibernate.wherejointable; | |||||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||||
| import java.util.List; | import java.util.List; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.ManyToMany; | import jakarta.persistence.ManyToMany; | ||||||
| 
 | 
 | ||||||
| @Entity(name = "e_group") | @Entity(name = "e_group") | ||||||
| public class Group { | public class Group { | ||||||
|  | |||||||
| @ -3,12 +3,12 @@ package com.baeldung.hibernate.wherejointable; | |||||||
| import java.util.ArrayList; | import java.util.ArrayList; | ||||||
| import java.util.List; | import java.util.List; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.JoinColumn; | import jakarta.persistence.JoinColumn; | ||||||
| import javax.persistence.JoinTable; | import jakarta.persistence.JoinTable; | ||||||
| import javax.persistence.ManyToMany; | import jakarta.persistence.ManyToMany; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.annotations.WhereJoinTable; | import org.hibernate.annotations.WhereJoinTable; | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -2,11 +2,11 @@ package com.baeldung.hibernate.wherejointable; | |||||||
| 
 | 
 | ||||||
| import java.io.Serializable; | import java.io.Serializable; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.EnumType; | import jakarta.persistence.EnumType; | ||||||
| import javax.persistence.Enumerated; | import jakarta.persistence.Enumerated; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity(name = "r_user_group") | @Entity(name = "r_user_group") | ||||||
| public class UserGroupRelation implements Serializable { | public class UserGroupRelation implements Serializable { | ||||||
|  | |||||||
| @ -7,12 +7,12 @@ | |||||||
|         <description>Hibernate EntityManager Demo</description>  |         <description>Hibernate EntityManager Demo</description>  | ||||||
|         <exclude-unlisted-classes>true</exclude-unlisted-classes> |         <exclude-unlisted-classes>true</exclude-unlisted-classes> | ||||||
|         <properties> |         <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="hibernate.hbm2ddl.auto" value="update"/> | ||||||
|             <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> |             <property name="jakarta.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="jakarta.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/> | ||||||
|             <property name="javax.persistence.jdbc.user" value="root"/> |             <property name="jakarta.persistence.jdbc.user" value="root"/> | ||||||
|             <property name="javax.persistence.jdbc.password" value="root"/> |             <property name="jakarta.persistence.jdbc.password" value="root"/> | ||||||
|         </properties> |         </properties> | ||||||
|     </persistence-unit> |     </persistence-unit> | ||||||
| </persistence>  | </persistence>  | ||||||
| @ -1,5 +1,6 @@ | |||||||
| package com.baeldung.hibernate.creationupdatetimestamp; | 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.assertEquals; | ||||||
| import static org.junit.jupiter.api.Assertions.assertNotEquals; | import static org.junit.jupiter.api.Assertions.assertNotEquals; | ||||||
| import static org.junit.jupiter.api.Assertions.assertNotNull; | import static org.junit.jupiter.api.Assertions.assertNotNull; | ||||||
| @ -71,22 +72,22 @@ class HibernateCreationUpdateTimestampIntegrationTest { | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreNotEqual() { |     void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() { | ||||||
|         session = sessionFactory.openSession(); |         session = sessionFactory.openSession(); | ||||||
|         session.beginTransaction(); |         session.beginTransaction(); | ||||||
|         Book book = new Book(); |         Book book = new Book(); | ||||||
| 
 | 
 | ||||||
|         session.save(book); |         session.save(book); | ||||||
|         session.getTransaction() |         session.getTransaction().commit(); | ||||||
|           .commit(); |  | ||||||
|         session.close(); |         session.close(); | ||||||
| 
 | 
 | ||||||
|         assertNotEquals(book.getCreatedOn(), book.getLastUpdatedOn()); |         assertEquals(book.getCreatedOn(), book.getLastUpdatedOn()); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() { |     void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() { | ||||||
|         session = sessionFactory.openSession(); |         session = sessionFactory.openSession(); | ||||||
|  |         session.setHibernateFlushMode(MANUAL); | ||||||
|         session.beginTransaction(); |         session.beginTransaction(); | ||||||
|         Book book = new Book(); |         Book book = new Book(); | ||||||
|         session.save(book); |         session.save(book); | ||||||
| @ -96,8 +97,9 @@ class HibernateCreationUpdateTimestampIntegrationTest { | |||||||
| 
 | 
 | ||||||
|         String newName = "newName"; |         String newName = "newName"; | ||||||
|         book.setTitle(newName); |         book.setTitle(newName); | ||||||
|         session.getTransaction() |         session.save(book); | ||||||
|           .commit(); |         session.flush(); | ||||||
|  |         session.getTransaction().commit(); | ||||||
|         session.close(); |         session.close(); | ||||||
|         Instant createdOnAfterUpdate = book.getCreatedOn(); |         Instant createdOnAfterUpdate = book.getCreatedOn(); | ||||||
|         Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn(); |         Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn(); | ||||||
|  | |||||||
| @ -6,10 +6,9 @@ import org.hibernate.boot.MetadataSources; | |||||||
| import org.hibernate.boot.registry.StandardServiceRegistryBuilder; | import org.hibernate.boot.registry.StandardServiceRegistryBuilder; | ||||||
| import org.hibernate.cfg.Environment; | import org.hibernate.cfg.Environment; | ||||||
| import org.hibernate.service.ServiceRegistry; | import org.hibernate.service.ServiceRegistry; | ||||||
| import org.junit.Assert; |  | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.TypedQuery; | import jakarta.persistence.TypedQuery; | ||||||
| import java.time.LocalDate; | import java.time.LocalDate; | ||||||
| import java.util.HashMap; | import java.util.HashMap; | ||||||
| import java.util.Map; | import java.util.Map; | ||||||
| @ -76,7 +75,7 @@ public class HibernateCustomTypesIntegrationTest { | |||||||
|         doInHibernate(this::sessionFactory, session -> { |         doInHibernate(this::sessionFactory, session -> { | ||||||
|             session.save(e); |             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); |             query.setParameter("pinCode",100); | ||||||
|             int size = query.getResultList().size(); |             int size = query.getResultList().size(); | ||||||
| 
 | 
 | ||||||
| @ -100,8 +99,8 @@ public class HibernateCustomTypesIntegrationTest { | |||||||
|         return metadata.buildSessionFactory(); |         return metadata.buildSessionFactory(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private static Map<String, String> getProperties() { |     private static Map<String, Object> getProperties() { | ||||||
|         Map<String, String> dbSettings = new HashMap<>(); |         Map<String, Object> dbSettings = new HashMap<>(); | ||||||
|         dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); |         dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1"); | ||||||
|         dbSettings.put(Environment.USER, "sa"); |         dbSettings.put(Environment.USER, "sa"); | ||||||
|         dbSettings.put(Environment.PASS, ""); |         dbSettings.put(Environment.PASS, ""); | ||||||
|  | |||||||
| @ -8,7 +8,7 @@ import org.hibernate.Session; | |||||||
| import org.junit.*; | import org.junit.*; | ||||||
| import org.junit.rules.ExpectedException; | import org.junit.rules.ExpectedException; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.PersistenceException; | import jakarta.persistence.PersistenceException; | ||||||
| 
 | 
 | ||||||
| import static org.hamcrest.MatcherAssert.assertThat; | import static org.hamcrest.MatcherAssert.assertThat; | ||||||
| import static org.hamcrest.core.IsEqual.equalTo; | import static org.hamcrest.core.IsEqual.equalTo; | ||||||
|  | |||||||
| @ -78,8 +78,8 @@ public class JoinColumnIntegrationTest { | |||||||
|         return metadata.buildSessionFactory(); |         return metadata.buildSessionFactory(); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private static Map<String, String> getProperties() { |     private static Map<String, Object> getProperties() { | ||||||
|         Map<String, String> dbSettings = new HashMap<>(); |         Map<String, Object> dbSettings = new HashMap<>(); | ||||||
|         dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1"); |         dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1"); | ||||||
|         dbSettings.put(Environment.USER, "sa"); |         dbSettings.put(Environment.USER, "sa"); | ||||||
|         dbSettings.put(Environment.PASS, ""); |         dbSettings.put(Environment.PASS, ""); | ||||||
|  | |||||||
| @ -78,10 +78,11 @@ | |||||||
|     </repositories> |     </repositories> | ||||||
| 
 | 
 | ||||||
|     <properties> |     <properties> | ||||||
|         <hibernate.version>5.3.7.Final</hibernate.version> |         <hibernate.version>6.1.7.Final</hibernate.version> | ||||||
|         <mysql.version>6.0.6</mysql.version> |         <mysql.version>8.0.32</mysql.version> | ||||||
|         <mariaDB4j.version>2.2.3</mariaDB4j.version> |         <mariaDB4j.version>2.6.0</mariaDB4j.version> | ||||||
|         <geodb.version>0.9</geodb.version> |         <geodb.version>0.9</geodb.version> | ||||||
|  |         <byte-buddy.version>1.14.2</byte-buddy.version> | ||||||
|     </properties> |     </properties> | ||||||
| 
 | 
 | ||||||
| </project> | </project> | ||||||
| @ -1,6 +1,6 @@ | |||||||
| package com.baeldung.hibernate.exception; | package com.baeldung.hibernate.exception; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class EntityWithNoId { | public class EntityWithNoId { | ||||||
|  | |||||||
| @ -1,9 +1,9 @@ | |||||||
| package com.baeldung.hibernate.exception; | package com.baeldung.hibernate.exception; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "PRODUCT") | @Table(name = "PRODUCT") | ||||||
|  | |||||||
| @ -1,8 +1,8 @@ | |||||||
| package com.baeldung.hibernate.exception; | package com.baeldung.hibernate.exception; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| @Table(name = "PRODUCT") | @Table(name = "PRODUCT") | ||||||
|  | |||||||
| @ -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; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -1,9 +1,9 @@ | |||||||
| package com.baeldung.hibernate.logging; | package com.baeldung.hibernate.logging; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class Employee { | public class Employee { | ||||||
|  | |||||||
| @ -1,11 +1,11 @@ | |||||||
| package com.baeldung.hibernate.pojo; | package com.baeldung.hibernate.pojo; | ||||||
| 
 | 
 | ||||||
| import com.vividsolutions.jts.geom.Point; | import org.locationtech.jts.geom.Point; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Column; | import jakarta.persistence.Column; | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class PointEntity { | public class PointEntity { | ||||||
|  | |||||||
| @ -1,10 +1,10 @@ | |||||||
| package com.baeldung.hibernate.pojo; | package com.baeldung.hibernate.pojo; | ||||||
| 
 | 
 | ||||||
| import com.vividsolutions.jts.geom.Polygon; | import org.locationtech.jts.geom.Polygon; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class PolygonEntity { | public class PolygonEntity { | ||||||
|  | |||||||
| @ -1,9 +1,9 @@ | |||||||
| package com.baeldung.hibernate.pojo; | package com.baeldung.hibernate.pojo; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.GenerationType; | import jakarta.persistence.GenerationType; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class Student { | public class Student { | ||||||
|  | |||||||
| @ -1,8 +1,8 @@ | |||||||
| package com.baeldung.persistence.model; | package com.baeldung.persistence.model; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.GeneratedValue; | import jakarta.persistence.GeneratedValue; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| 
 | 
 | ||||||
| @Entity | @Entity | ||||||
| public class Person { | public class Person { | ||||||
|  | |||||||
| @ -7,12 +7,12 @@ | |||||||
|         <description>Hibernate EntityManager Demo</description>  |         <description>Hibernate EntityManager Demo</description>  | ||||||
|         <exclude-unlisted-classes>true</exclude-unlisted-classes> |         <exclude-unlisted-classes>true</exclude-unlisted-classes> | ||||||
|         <properties> |         <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="hibernate.hbm2ddl.auto" value="update"/> | ||||||
|             <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/> |             <property name="jakarta.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="jakarta.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/moviecatalog"/> | ||||||
|             <property name="javax.persistence.jdbc.user" value="root"/> |             <property name="jakarta.persistence.jdbc.user" value="root"/> | ||||||
|             <property name="javax.persistence.jdbc.password" value="root"/> |             <property name="jakarta.persistence.jdbc.password" value="root"/> | ||||||
|         </properties> |         </properties> | ||||||
|     </persistence-unit> |     </persistence-unit> | ||||||
| </persistence>  | </persistence>  | ||||||
| @ -9,23 +9,23 @@ import java.io.IOException; | |||||||
| import java.net.URL; | import java.net.URL; | ||||||
| import java.util.Properties; | import java.util.Properties; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Query; | import jakarta.persistence.Query; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.Session; | import org.hibernate.Session; | ||||||
| import org.hibernate.Transaction; | import org.hibernate.Transaction; | ||||||
| import org.junit.After; | import org.junit.After; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| import org.junit.Test; | 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.PointEntity; | ||||||
| import com.baeldung.hibernate.pojo.PolygonEntity; | 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; | import geodb.GeoDB; | ||||||
| 
 | 
 | ||||||
| @ -39,7 +39,7 @@ public class HibernateSpatialIntegrationTest { | |||||||
|         session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") |         session = HibernateUtil.getSessionFactory("hibernate-spatial.properties") | ||||||
|           .openSession(); |           .openSession(); | ||||||
|         transaction = session.beginTransaction(); |         transaction = session.beginTransaction(); | ||||||
|         session.doWork(conn -> { GeoDB.InitGeoDB(conn); }); |         session.doWork(GeoDB::InitGeoDB); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @After |     @After | ||||||
| @ -135,9 +135,7 @@ public class HibernateSpatialIntegrationTest { | |||||||
| 
 | 
 | ||||||
|     private Geometry wktToGeometry(String wellKnownText) throws ParseException { |     private Geometry wktToGeometry(String wellKnownText) throws ParseException { | ||||||
|         WKTReader fromText = new WKTReader(); |         WKTReader fromText = new WKTReader(); | ||||||
|         Geometry geom = null; |         return fromText.read(wellKnownText); | ||||||
|         geom = fromText.read(wellKnownText); |  | ||||||
|         return geom; |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     private static Geometry createCircle(double x, double y, double radius) { |     private static Geometry createCircle(double x, double y, double radius) { | ||||||
|  | |||||||
| @ -6,28 +6,25 @@ import static org.junit.Assert.assertNotNull; | |||||||
| import java.io.IOException; | import java.io.IOException; | ||||||
| import java.util.List; | import java.util.List; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.OptimisticLockException; | import jakarta.persistence.OptimisticLockException; | ||||||
| import javax.persistence.PersistenceException; | import jakarta.persistence.PersistenceException; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.AnnotationException; |  | ||||||
| import org.hibernate.HibernateException; | import org.hibernate.HibernateException; | ||||||
| import org.hibernate.MappingException; | import org.hibernate.MappingException; | ||||||
| import org.hibernate.NonUniqueObjectException; | import org.hibernate.NonUniqueObjectException; | ||||||
| import org.hibernate.PropertyValueException; | import org.hibernate.PropertyValueException; | ||||||
| import org.hibernate.Session; | import org.hibernate.Session; | ||||||
| import org.hibernate.SessionFactory; | import org.hibernate.SessionFactory; | ||||||
| import org.hibernate.StaleObjectStateException; |  | ||||||
| import org.hibernate.StaleStateException; | import org.hibernate.StaleStateException; | ||||||
| import org.hibernate.Transaction; | import org.hibernate.Transaction; | ||||||
| import org.hibernate.TransactionException; |  | ||||||
| import org.hibernate.cfg.AvailableSettings; | import org.hibernate.cfg.AvailableSettings; | ||||||
| import org.hibernate.cfg.Configuration; | import org.hibernate.cfg.Configuration; | ||||||
| import org.hibernate.exception.ConstraintViolationException; | import org.hibernate.exception.ConstraintViolationException; | ||||||
| import org.hibernate.exception.DataException; | import org.hibernate.exception.DataException; | ||||||
| import org.hibernate.exception.SQLGrammarException; | import org.hibernate.exception.SQLGrammarException; | ||||||
| import org.hibernate.hql.internal.ast.QuerySyntaxException; |  | ||||||
| import org.hibernate.id.IdentifierGenerationException; | import org.hibernate.id.IdentifierGenerationException; | ||||||
| import org.hibernate.query.NativeQuery; | import org.hibernate.query.NativeQuery; | ||||||
|  | import org.hibernate.query.sqm.UnknownEntityException; | ||||||
| import org.hibernate.tool.schema.spi.CommandAcceptanceException; | import org.hibernate.tool.schema.spi.CommandAcceptanceException; | ||||||
| import org.hibernate.tool.schema.spi.SchemaManagementException; | import org.hibernate.tool.schema.spi.SchemaManagementException; | ||||||
| import org.junit.Before; | import org.junit.Before; | ||||||
| @ -63,12 +60,15 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { |     public void whenQueryExecutedWithUnmappedEntity_thenMappingException() { | ||||||
|         thrown.expectCause(isA(MappingException.class)); |         thrown.expect(isA(MappingException.class)); | ||||||
|         thrown.expectMessage("Unknown entity: java.lang.String"); |         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(); |         Session session = sessionFactory.openSession(); | ||||||
|         NativeQuery<String> query = session.createNativeQuery("select name from PRODUCT", String.class); |         session.save(product); | ||||||
|         query.getResultList(); |  | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
| @ -82,8 +82,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() { |     public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() { | ||||||
|         thrown.expectCause(isA(QuerySyntaxException.class)); |         thrown.expectCause(isA(UnknownEntityException.class)); | ||||||
|         thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]"); |         thrown.expectMessage("Could not resolve root entity 'PRODUCT"); | ||||||
| 
 | 
 | ||||||
|         Session session = sessionFactory.openSession(); |         Session session = sessionFactory.openSession(); | ||||||
|         List<Product> results = session.createQuery("from PRODUCT", Product.class) |         List<Product> results = session.createQuery("from PRODUCT", Product.class) | ||||||
| @ -92,8 +92,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { |     public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() { | ||||||
|         thrown.expect(AnnotationException.class); |         thrown.expect(isA(HibernateException.class)); | ||||||
|         thrown.expectMessage("No identifier specified for entity"); |         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(); |         Configuration cfg = getConfiguration(); | ||||||
|         cfg.addAnnotatedClass(EntityWithNoId.class); |         cfg.addAnnotatedClass(EntityWithNoId.class); | ||||||
| @ -132,9 +132,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { |     public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() { | ||||||
|         thrown.expect(isA(PersistenceException.class)); |  | ||||||
|         thrown.expectCause(isA(SQLGrammarException.class)); |         thrown.expectCause(isA(SQLGrammarException.class)); | ||||||
|         thrown.expectMessage("SQLGrammarException: could not prepare statement"); |         thrown.expectMessage("could not prepare statement"); | ||||||
| 
 | 
 | ||||||
|         Configuration cfg = getConfiguration(); |         Configuration cfg = getConfiguration(); | ||||||
|         cfg.addAnnotatedClass(Product.class); |         cfg.addAnnotatedClass(Product.class); | ||||||
| @ -162,9 +161,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { |     public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() { | ||||||
|         thrown.expect(isA(PersistenceException.class)); |  | ||||||
|         thrown.expectCause(isA(SQLGrammarException.class)); |         thrown.expectCause(isA(SQLGrammarException.class)); | ||||||
|         thrown.expectMessage("SQLGrammarException: could not prepare statement"); |         thrown.expectMessage("could not prepare statement"); | ||||||
| 
 | 
 | ||||||
|         Session session = sessionFactory.openSession(); |         Session session = sessionFactory.openSession(); | ||||||
|         NativeQuery<Product> query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class); |         NativeQuery<Product> query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class); | ||||||
| @ -173,9 +171,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenDuplicateIdSaved_thenConstraintViolationException() { |     public void whenDuplicateIdSaved_thenConstraintViolationException() { | ||||||
|         thrown.expect(isA(PersistenceException.class)); |  | ||||||
|         thrown.expectCause(isA(ConstraintViolationException.class)); |         thrown.expectCause(isA(ConstraintViolationException.class)); | ||||||
|         thrown.expectMessage("ConstraintViolationException: could not execute statement"); |         thrown.expectMessage("could not execute statement"); | ||||||
| 
 | 
 | ||||||
|         Session session = null; |         Session session = null; | ||||||
|         Transaction transaction = null; |         Transaction transaction = null; | ||||||
| @ -253,7 +250,7 @@ public class HibernateExceptionUnitTest { | |||||||
|     @Test |     @Test | ||||||
|     public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() { |     public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() { | ||||||
|         thrown.expectCause(isA(DataException.class)); |         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(); |         Session session = sessionFactory.openSession(); | ||||||
|         NativeQuery<Product> query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class); |         NativeQuery<Product> query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class); | ||||||
| @ -330,9 +327,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void whenUpdatingNonExistingObject_thenStaleStateException() { |     public void whenUpdatingNonExistingObject_thenStaleStateException() { | ||||||
|         thrown.expect(isA(OptimisticLockException.class)); |         thrown.expectCause(isA(StaleStateException.class)); | ||||||
|         thrown.expectMessage("Row was updated or deleted by another transaction"); |         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=?"); | ||||||
|         thrown.expectCause(isA(StaleObjectStateException.class)); |  | ||||||
| 
 | 
 | ||||||
|         Session session = null; |         Session session = null; | ||||||
|         Transaction transaction = null; |         Transaction transaction = null; | ||||||
| @ -356,7 +352,8 @@ public class HibernateExceptionUnitTest { | |||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { |     public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() { | ||||||
|         thrown.expect(isA(TransactionException.class)); |         thrown.expect(isA(IllegalStateException.class)); | ||||||
|  |         thrown.expectMessage("Transaction already active"); | ||||||
| 
 | 
 | ||||||
|         Session session = null; |         Session session = null; | ||||||
|         Transaction transaction = null; |         Transaction transaction = null; | ||||||
| @ -368,6 +365,7 @@ public class HibernateExceptionUnitTest { | |||||||
|             product1.setId(15); |             product1.setId(15); | ||||||
|             product1.setName("Product1"); |             product1.setName("Product1"); | ||||||
|             session.save(product1); |             session.save(product1); | ||||||
|  |             transaction = session.beginTransaction(); | ||||||
|             transaction.setRollbackOnly(); |             transaction.setRollbackOnly(); | ||||||
| 
 | 
 | ||||||
|             transaction.commit(); |             transaction.commit(); | ||||||
|  | |||||||
| @ -2,9 +2,9 @@ package com.baeldung.hibernate.multitenancy; | |||||||
| 
 | 
 | ||||||
| import java.io.Serializable; | import java.io.Serializable; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.Entity; | import jakarta.persistence.Entity; | ||||||
| import javax.persistence.Id; | import jakarta.persistence.Id; | ||||||
| import javax.persistence.Table; | import jakarta.persistence.Table; | ||||||
| 
 | 
 | ||||||
| @Entity(name = "Car") | @Entity(name = "Car") | ||||||
| @Table(name = "Car") | @Table(name = "Car") | ||||||
|  | |||||||
| @ -79,9 +79,9 @@ public abstract class MultitenancyIntegrationTest { | |||||||
|     private void createCarTable() { |     private void createCarTable() { | ||||||
|         Session session = sessionFactory.openSession(); |         Session session = sessionFactory.openSession(); | ||||||
|         Transaction tx = session.beginTransaction(); |         Transaction tx = session.beginTransaction(); | ||||||
|         session.createSQLQuery("drop table Car if exists") |         session.createNativeQuery("drop table Car if exists") | ||||||
|             .executeUpdate(); |             .executeUpdate(); | ||||||
|         session.createSQLQuery("create table Car (brand varchar(255) primary key)") |         session.createNativeQuery("create table Car (brand varchar(255) primary key)") | ||||||
|             .executeUpdate(); |             .executeUpdate(); | ||||||
|         tx.commit(); |         tx.commit(); | ||||||
|     } |     } | ||||||
|  | |||||||
| @ -1,7 +1,5 @@ | |||||||
| package com.baeldung.hibernate.multitenancy.database; | package com.baeldung.hibernate.multitenancy.database; | ||||||
| 
 | 
 | ||||||
| import java.io.IOException; |  | ||||||
| 
 |  | ||||||
| import org.junit.Test; | import org.junit.Test; | ||||||
| 
 | 
 | ||||||
| import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; | import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest; | ||||||
| @ -14,7 +12,7 @@ public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyInt | |||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|     @Test |     @Test | ||||||
|     public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException { |     public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() { | ||||||
|         whenCurrentTenantIs(TenantIdNames.MYDB1); |         whenCurrentTenantIs(TenantIdNames.MYDB1); | ||||||
|         whenAddCar("myCar"); |         whenAddCar("myCar"); | ||||||
|         thenCarFound("myCar"); |         thenCarFound("myCar"); | ||||||
|  | |||||||
| @ -34,8 +34,13 @@ public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnect | |||||||
|     private void initConnectionProviderForTenant(String tenantId) throws IOException { |     private void initConnectionProviderForTenant(String tenantId) throws IOException { | ||||||
|         Properties properties = new Properties(); |         Properties properties = new Properties(); | ||||||
|         properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId))); |         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(); |         DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); | ||||||
|         connectionProvider.configure(properties); |         connectionProvider.configure(configProperties); | ||||||
|         this.connectionProviderMap.put(tenantId, connectionProvider); |         this.connectionProviderMap.put(tenantId, connectionProvider); | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -3,6 +3,8 @@ package com.baeldung.hibernate.multitenancy.schema; | |||||||
| import java.io.IOException; | import java.io.IOException; | ||||||
| import java.sql.Connection; | import java.sql.Connection; | ||||||
| import java.sql.SQLException; | import java.sql.SQLException; | ||||||
|  | import java.util.HashMap; | ||||||
|  | import java.util.Map; | ||||||
| import java.util.Properties; | import java.util.Properties; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; | import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl; | ||||||
| @ -39,9 +41,14 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn | |||||||
|     private ConnectionProvider initConnectionProvider() throws IOException { |     private ConnectionProvider initConnectionProvider() throws IOException { | ||||||
|         Properties properties = new Properties(); |         Properties properties = new Properties(); | ||||||
|         properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.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(); |         DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl(); | ||||||
|         connectionProvider.configure(properties); |         connectionProvider.configure(configProperties); | ||||||
|         return connectionProvider; |         return connectionProvider; | ||||||
|     } |     } | ||||||
| 
 | 
 | ||||||
|  | |||||||
| @ -7,7 +7,7 @@ import static org.junit.Assert.assertNotSame; | |||||||
| import static org.junit.Assert.assertNull; | import static org.junit.Assert.assertNull; | ||||||
| import static org.junit.Assert.assertSame; | import static org.junit.Assert.assertSame; | ||||||
| 
 | 
 | ||||||
| import javax.persistence.PersistenceException; | import jakarta.persistence.PersistenceException; | ||||||
| 
 | 
 | ||||||
| import org.hibernate.HibernateException; | import org.hibernate.HibernateException; | ||||||
| import org.hibernate.Session; | import org.hibernate.Session; | ||||||
|  | |||||||
| @ -12,5 +12,3 @@ hibernate.c3p0.min_size=5 | |||||||
| hibernate.c3p0.max_size=20 | hibernate.c3p0.max_size=20 | ||||||
| hibernate.c3p0.acquire_increment=5 | hibernate.c3p0.acquire_increment=5 | ||||||
| hibernate.c3p0.timeout=1800 | hibernate.c3p0.timeout=1800 | ||||||
| 
 |  | ||||||
| hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory |  | ||||||
|  | |||||||
| @ -4,7 +4,7 @@ hibernate.connection.username=sa | |||||||
| hibernate.connection.autocommit=true | hibernate.connection.autocommit=true | ||||||
| jdbc.password= | jdbc.password= | ||||||
| 
 | 
 | ||||||
| hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect | hibernate.dialect=org.hibernate.dialect.H2Dialect | ||||||
| hibernate.show_sql=true | hibernate.show_sql=true | ||||||
| hibernate.hbm2ddl.auto=create-drop | hibernate.hbm2ddl.auto=create-drop | ||||||
| 
 | 
 | ||||||
|  | |||||||
Some files were not shown because too many files have changed in this diff Show More
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user