Spring Boot MySQL : Table ‘DB_NAME.hibernate_sequence’ doesn’t exist

Spring Boot + Spring Data JPA + MySQL, and hits the following error message when the application starts : Tested with : Spring Boot 2.1.2.RELEASE mysql-connector-java 8.0.13 Hibernate 5.3.7 java.sql.SQLSyntaxErrorException: Table ‘DB_NAME.hibernate_sequence’ doesn’t exist at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974) at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1024) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216) at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46) application.properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=mkyong …

Read more

Spring Boot + Spring Data JPA + MySQL example

This article shows how to use Spring Web MVC to create REST endpoints to perform CRUD database operations using the Spring Data JPA and MySQL. At the end of the tutorial, we will use Docker to start a MySQL container to test the Spring Boot REST endpoints using curl commands. We will use Spring Test …

Read more

Spring Boot + Spring Data JPA example

This article shows how to use Spring Data JPA to perform CRUD operation into a H2 in-memory database. Technologies used: Spring Boot 3.1.2 Spring Data JPA (Hibernate 6 is the default JPA implementation) H2 in-memory database Maven Java 17 Table of contents: 1. Project Directory 2. Project Dependencies 3. Spring Data JPA – Entity 4. …

Read more

JDBC PreparedStatement SQL IN condition

Java JDBC PreparedStatement example to create a SQL IN condition. 1. PreparedStatement + Array In JDBC, we can use createArrayOf to create a PreparedStatement IN query. @Override public List<Integer> getPostIdByTagId(List<Integer> tagIds) { List<Integer> result = new ArrayList<>(); String sql = "SELECT tr.object_id as post_id FROM wp_term_relationships tr " + " JOIN wp_term_taxonomy tt JOIN wp_terms …

Read more

Java 8 – Convert a Stream to Array

In Java 8, we can use .toArray() to convert a Stream into an Array. 1. Stream -> String[] StreamString.java package com.mkyong; import java.util.Arrays; public class StreamString { public static void main(String[] args) { String lines = "I Love Java 8 Stream!"; // split by space, uppercase, and convert to Array String[] result = Arrays.stream(lines.split("\\s+")) .map(String::toUpperCase) …

Read more

HikariPool-1 – Connection is not available, request timed out after 30002ms.

After some SQL queries, the system is unable to get any connection from the HikariPool and prompts the following error message HikariPool-1 – Connection is not available, request timed out after 30002ms. Tested with HikariCP 3.3.1 mysql-connector-java 5.1.47 Java 8 1. Solution 1.1 Enable the debug logs for com.zaxxer.hikari, it will print out many useful …

Read more

Java 8 – How to convert IntStream to Integer[]

The key is boxed() the IntStream into a Stream<Integer>, then only convert to an Array. StreamExample.java package com.mkyong; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; public class StreamExample { public static void main(String[] args) { //int[] -> IntStream -> Stream<Integer> -> Integer[] int[] num = {3, 4, 5}; //1. int[] -> IntStream IntStream stream = Arrays.stream(num); …

Read more

Java – How to declare and initialize an Array

Few Java examples to declare, initialize and manipulate Array in Java 1. Declares Array 1.1 For primitive types. ArrayExample1.java package com.mkyong; import java.util.Arrays; public class ArrayExample1 { public static void main(String[] args) { //declares an array of integers int[] num1 = new int[5]; int[] num2 = {1, 2, 3, 4, 5}; int[] num3 = new …

Read more

Spring Boot YAML example

In this article, we will show you how to use YAML instead of properties file in Spring Boot. Tested with : Spring Boot 2.1.2.RELEASE Maven 3 Snakeyaml:jar:1.23 In short, create a application.yml in the src/resources folder, Spring Boot will load and parse .yml file automatically and bind the values into the classes which annotated with …

Read more

Spring Boot – Run code when the application starts

In Spring Boot, we can create a CommandLineRunner bean to run code when the application is fully started. StartBookApplication.java package com.mkyong; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @SpringBootApplication public class StartBookApplication { public static void main(String[] args) { SpringApplication.run(StartBookApplication.class, args); } // Injects …

Read more

Java 8 – How to sort list with stream.sorted()

Few examples to show you how to sort a List with stream.sorted() 1. List 1.1 Sort a List with Comparator.naturalOrder() package com.mkyong.sorted; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamApplication { public static void main(String[] args) { List<String> list = Arrays.asList("9", "A", "Z", "1", "B", "Y", "4", "a", "c"); /* List<String> sortedList = list.stream() …

Read more

How to backup MySQL / MariaDB database to Amazon S3, shell script example

This article shows a shell script to backup or export a MySQL / MariaDB database, gzip the exported file, and upload the gzipped backup file to Amazon S3. Table of contents 1. Install AWS CLI 2. Backup MySQL/MariaDB database to S3 (Shell Script) 3. How to run the backup script? 4. Run the backup script …

Read more

Spring REST Integration Test Example

In this article, we will show you how to test the Spring Boot REST application. Normally, we use the MockMvc or TestRestTemplate for the integration test. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 pom.xml <!– spring integration test –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!– spring integration test for security–> …

Read more

Spring Test – How to test a JSON Array in jsonPath

In Spring, we can use Hamcrest APIs like hasItem and hasSize to test a JSON Array. Review the following example : package com.mkyong; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import …

Read more

Spring + Mockito – Unable to mock save method?

Try to mock a repository save() method, but it is always returning null? P.S Tested with Spring Boot 2 + Spring Data JPA @Test public void save_book_OK() throws Exception { Book newBook = new Book(1L, "Mockito Guide", "mkyong"); when(mockRepository.save(newBook)).thenReturn(newBook); mockMvc.perform(post("/books") .content("{json}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); } Solution 1. Mockito uses the equals for argument matching, try …

Read more

Java – Convert Integer to String

In Java, you can use String.valueOf() to convert an Integer to String. 1. String.valueOf 1.1 Example to convert an Integer or int 10 to a String. Integer num = 10; //int num = 10; String numInString = String.valueOf(num); System.out.println(numInString); Output 10 2. toString() It works on Integer object only. Integer num = 10; String numInString …

Read more

Spring Boot – How to init a Bean for testing?

In Spring Boot, we can create a @TestConfiguration class to initialize some beans for testing class only. P.S Tested with Spring Boot 2 1. @TestConfiguration + @Import This @TestConfiguration class will not pick up by the component scanning, we need to import it manually. TestConfig.java package com.mkyong; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import java.time.Duration; …

Read more

How to compare strings in Java

In Java, we use equals() to compare string value. String str1 = "apple"; // compare strings case-sensitive if (str1.equals("apple")) { System.out.println("I have an apple."); } String str2 = "apple"; // compare strings case-insensitive if (str2.equalsIgnoreCase("APPLE")) { System.out.println("I have an APPLE."); } Output Terminal I have an apple. I have an APPLE. In this article, we …

Read more

Mockito – How to mock repository findById thenReturn() Optional?

Try to mock a repository findById method, but no idea use thenReturn() to return an object, as it accepts an Optional? P.S Tested in Spring Boot 2 environment import static org.mockito.Mockito.*; import org.springframework.boot.test.mock.mockito.MockBean; @MockBean private BookRepository mockRepository; @Before public void init() { Book book = new Book(1L, "A Book"); //error, can’t resolve method thenReturn(book)? when(mockRepository.findById(1L)).thenReturn(book); …

Read more

Spring REST Error Handling Example

In this article, we will show you error handling in Spring Boot REST application. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 1. /error 1.1 By default, Spring Boot provides a BasicErrorController controller for /error mapping that handles all errors, and getErrorAttributes to produce a JSON response with details of the …

Read more

JSONAssert – How to unit test JSON data

In Java, we can use JSONAssert to unit test JSON data easily. 1. Maven pom.xml <dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>1.5.0</version> </dependency> 2. JSON Object To test the JSON Object, Strict or not, fields order does not matter. If the extended fields are matter, enable the strict mode. 2.1 When the strictMode is off. JSONObject actual = …

Read more

Spring REST + Spring Security Example

In this article, we will enhance the previous Spring REST Validation Example, by adding Spring Security to perform authentication and authorization for the requested URLs (REST API endpoints) Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Spring Security 5.1.3.RELEASE Spring Data JPA 2.1.4.RELEASE H2 In-memory Database 1.4.197 Tomcat Embed 9.0.14 JUnit 4.12 Maven 3 Java …

Read more

Spring Security – There is no PasswordEncoder mapped for the id “null”

Send a GET request with username and password, but hits the password encoder error? Tested Spring Boot 2.1.2.RELEASE 5.1.3.RELEASE $ curl localhost:8080/books -u user:password { "timestamp":"2019-02-22T15:03:49.322+0000", "status":500, "error":"Internal Server Error", "message":"There is no PasswordEncoder mapped for the id \"null\"", "path":"/books" } errors in logs java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" Here …

Read more

Spring Boot Test unable to autowired MockMvc

Spring Boot integeration test, but unable to @Autowired MockMvc P.S Tested with Spring Boot 2.1.2.RELEASE BookControllerTest.java package com.mkyong; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class BookControllerTest { @Autowired …

Read more

Spring REST Validation Example

In this article, we will enhance the previous Spring REST Hello World example, by adding bean validation and custom validator. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 1. Controller Review the previous REST Controller again : BookController.java package com.mkyong; import com.mkyong.error.BookNotFoundException; import com.mkyong.error.BookUnSupportedFieldPatchException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import …

Read more

Spring REST Hello World Example

In this article, we will show you how to develop a Spring Boot REST style web service to handle CRUD operations from a H2 In-memory database. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Spring Data JPA 2.1.4.RELEASE H2 In-memory Database 1.4.197 Tomcat Embed 9.0.14 JUnit 4.12 Maven 3 Java 8 1. Project Directory 2. …

Read more

Mockito – when() requires an argument which has to be ‘a method call on a mock’

Run the following Spring Boot + JUnit 5 + Mockito integration test. package com.mkyong.core.services; import com.mkyong.core.repository.HelloRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; @SpringBootTest public class HelloServiceMockTest { @Mock private HelloRepository helloRepository; @InjectMocks // auto inject helloRepository private HelloService helloService = new HelloServiceImpl(); @BeforeEach …

Read more

Spring Boot + JUnit 5 + Mockito

In this article, we will show you how to do Spring Boot 2 integration test with JUnit 5, and also Mockito. Spring Boot 2.1.2.RELEASE JUnit 5 Mockito 2 Maven 3 In short, exclude junit4 from spring-boot-starter-test, and include the JUnit 5 jupiter engine manually, done. Let see the following Spring boot MVC web application, and …

Read more

Spring Boot WebFlux + Server-sent events example

In this article, we will show you how to develop a reactive web application, using Server-sent events Spring Boot 2.1.2.RELEASE Spring WebFlux 5.1.4.RELEASE Thymeleaf 3.0.11.RELEASE JUnit 5.3.2 Maven 3 In Spring, returns JSON and header MediaType.TEXT_EVENT_STREAM_VALUE @RestController public class CommentController { @GetMapping(path = "/comment/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<Comment> feed() { //… } } In …

Read more

Spring Boot WebFlux + Thymeleaf reactive example

In this article, we will show you how to develop a reactive web application. Spring Boot 2.1.2.RELEASE Spring WebFlux 5.1.4.RELEASE Thymeleaf 3.0.11.RELEASE Maven 3 Spring Boot will configure everything, and the key is using the Thymeleaf ReactiveDataDriverContextVariable to enable the data-driven mode in Thymeleaf template. @RequestMapping("/") public String index(final Model model) { // data streaming, …

Read more

An Introduction to Kernel Live Patching on Linux

Live patching is slowly catching on, but not for the reasons you might think. In this article, I’ll explain what Linux kernel live patching is, what it isn’t, what services there are, who might use it and why. I’ll show the basic installation steps for Livepatch (on Ubuntu), Kpatch (on Red Hat), and one other, …

Read more

log4j2 – Failed to load class “org.slf4j.impl.StaticLoggerBinder”

The Java project is using log4j2, but look like some components are used SLF4J logging and caused the following error message: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Solution To fix it, we need a SLF4J Bridge. Puts log4j-slf4j-impl in the classpath. pom.xml …

Read more

cURL post JSON data on Windows

On Windows, the key to send JSON data is double-quotes like this -d "{\"name\":\"Spring Forever\"}" cURL to POST a JSON data curl -X POST localhost:8080/books -H "Content-type:application/json" -d "{\"name\":\"Spring Forever\",\"author\":\"pivotal\"}" References cURL – Post JSON data to Spring REST

Java ArrayIndexOutOfBoundsException example

This java.lang.ArrayIndexOutOfBoundsException is thrown when we are accessing an array with an index which is greater than the size of an array. P.S Array index starts with 0 ArrayExample.java package com.mkyong; public class ArrayExample { public static void main(String[] args) { // array of 3 int[] num = new int[3]; num[0] = 1; num[1] = …

Read more

Spring WebFlux Test – Timeout on blocking read for 5000 MILLISECONDS

Test a Spring Webflux endpoint with the WebTestClient, and hits the following error messages. Is this possible to increase the timeout? java.lang.IllegalStateException: Timeout on blocking read for 5000 MILLISECONDS at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:117) at reactor.core.publisher.Mono.block(Mono.java:1524) at org.springframework.test.web.reactive.server.ExchangeResult.formatBody(ExchangeResult.java:247) at org.springframework.test.web.reactive.server.ExchangeResult.toString(ExchangeResult.java:216) at java.base/java.lang.String.valueOf(String.java:2788) at java.base/java.lang.StringBuilder.append(StringBuilder.java:135) at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:200) Solution By default, the WebTestClient will be timeout after 5 seconds. We …

Read more

Java – How to run Windows bat file

In Java, we can use ProcessBuilder to run a Windows batch file like this : ProcessBuilder processBuilder = new ProcessBuilder("C:\\Users\\mkyong\\hello.bat"); //or ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("cmd", "/c", "hello.bat"); File dir = new File("C:\\Users\\mkyong\\"); processBuilder.directory(dir); Alternatively, Runtime.getRuntime().exec like this : Process process = Runtime.getRuntime().exec( "cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\")); 1. Java Example 1.1 A …

Read more

Java – How to list all files in a directory?

Two Java examples to show you how to list files in a directory : For Java 8, Files.walk Before Java 8, create a recursive loop to list all files. 1. Files.walk 1.1 List all files. try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); …

Read more

Java ProcessBuilder examples

In Java, we can use ProcessBuilder to call external commands easily : ProcessBuilder processBuilder = new ProcessBuilder(); // — Linux — // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script processBuilder.command("path/to/hello.sh"); // — Windows — // Run a command processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\mkyong"); // Run a bat file processBuilder.command("C:\\Users\\mkyong\\hello.bat"); Process …

Read more