Spring Boot + Spring Data JPA + Java 8 date and time (JSR310)

In Spring Boot + Spring Data JPA application, to support the JSR310 java.time.* APIs, we need to register this Jsr310JpaConverters manually. import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; @EntityScan( basePackageClasses = {Application.class, Jsr310JpaConverters.class} ) @SpringBootApplication public class Application { //… } P.S Tested with Spring Boot 1.5.1.RELEASE, Spring Data JPA 1.11.0.RELEASE 1. Full Example 1.1 A model contains …

Read more

How to display all beans loaded by Spring Boot

In Spring Boot, you can use appContext.getBeanDefinitionNames() to get all the beans loaded by the Spring container. 1. CommandLineRunner as Interface Application.java package com.mkyong; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.Arrays; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private ApplicationContext appContext; public static void main(String[] args) throws Exception { …

Read more

Spring Data – Add custom method to Repository

In this article, we will show you how to add a custom method to Spring Data JPA CrudRepository and MongoDB MongoRepository 1. CrudRepository 1.1 Review a CustomerRepository, we will add a custom method to this repository. CustomerRepository.java package com.mkyong.dao; import com.mkyong.model.Customer; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.List; import java.util.stream.Stream; public interface …

Read more

Spring Boot + Spring Data MongoDB example

In this article, we will show you how to create a Spring Boot + Spring Data MongoDB application, using Gradle build tool. Spring Boot 1.5.1.RELEASE MongoDB Gradle Java 8 1. Project Structure A standard project structure. 2. Project Dependency 2.1 A Gradle build file. build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.1.RELEASE") } …

Read more

JPA Insert + Oracle Sequences example

A quick JPA + Oracle sequences example, for self reference. 1. Oracle Database Issue the following SQL script to create a table and a sequence. CREATE TABLE CUSTOMER( ID NUMBER(10) NOT NULL, NAME VARCHAR2(100) NOT NULL, EMAIL VARCHAR2(100) NOT NULL, CREATED_DATE DATE NOT NULL, CONSTRAINT CUSTOMER_PK PRIMARY KEY (ID) ); CREATE SEQUENCE customer_seq MINVALUE 1 …

Read more

Oracle PL/SQL – Rename Trigger

This article shows you how to use ALTER TRIGGER to rename a trigger. — rename a trigger ALTER TRIGGER original_name RENAME TO new_name; 1. Table + Trigger electricity_bill create table electricity_bill ( bill_id number(5) primary key, amount number(5) ); — Table ELECTRICITY_BILL created. trg_rename_example CREATE OR REPLACE TRIGGER trg_rename_example BEFORE UPDATE OR DELETE OR INSERT …

Read more

Spring Boot – Show Hibernate SQL query

Add the following lines in application.properties to log the Hibernate SQL query. application.properties #show sql statement logging.level.org.hibernate.SQL=debug #show sql values logging.level.org.hibernate.type.descriptor.sql=trace 1. org.hibernate.SQL=debug application.properties logging.level.org.hibernate.SQL=debug 1.1 Select query. Console 2017-02-23 21:36:42 DEBUG org.hibernate.SQL – select customer0_.id as id1_0_, customer0_.created_date as created_date2_0_, customer0_.email as email3_0_, customer0_.name as name4_0_ from customer customer0_ 2. org.hibernate.type.descriptor.sql=trace application.properties logging.level.org.hibernate.SQL=debug logging.level.org.hibernate.type.descriptor.sql=trace …

Read more

Java 8 Optional In Depth

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or …

Read more

Spring Boot + Spring Data JPA + Oracle example

In this article, we will show you how to create a Spring Boot + Spring Data JPA + Oracle + HikariCP connection pool example. Tools used in this article : Spring Boot 1.5.1.RELEASE Spring Data 1.13.0.RELEASE Hibernate 5 Oracle database 11g express Oracle JDBC driver ojdbc7.jar HikariCP 2.6 Maven Java 8 1. Project Structure A …

Read more

WordPress – Disable comments on attachments

After stopped and cleaned the WordPress pingback and trackback spams, those spammers have changed strategy to start spamming comments and trackbacks on the post attachments. Solution 1.1 Stop commenting on new and existing attachment. Add below PHP script in theme’s function.php ${theme_folder}/function.php //disable comments on attachment function filter_media_comment_status( $open, $post_id ) { $post = get_post( …

Read more

Spring Boot JDBC + Oracle database + Commons DBCP2 example

In this article, we will show you how to create a Spring Boot JDBC application + Oracle database + Commons DBCP2 connection pool. Tools used in this article : Spring Boot 1.5.1.RELEASE Oracle database 11g express Oracle JDBC driver ojdbc7.jar Commons DBCP2 2.1.1 Maven Java 8 Note Related – Spring Boot JDBC + MySQL + …

Read more

Spring Boot – How to know which connection pool is used?

In Spring Boot, @Autowired a javax.sql.DataSource, and you will know which database connection pool is using in the current running application. 1. Test Default Spring Boot example to print a javax.sql.DataSource Note Read this official Spring Boot doc – Connection to a production database, to understand the algorithm for choosing a DataSource implementations – Tomcat …

Read more

MySQL – Establishing SSL connection without server’s identity verification is not recommended

Start a Spring Boot application and making a JDBC connection, hits the following warning messages on console : Fri Feb 10 18:43:02 SGT 2017 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. …

Read more

Spring Boot non-web application example

In Spring Boot, to create a non-web application, implements CommandLineRunner and override the run method, for example : import org.springframework.boot.CommandLineRunner; @SpringBootApplication public class SpringBootConsoleApplication implements CommandLineRunner { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootConsoleApplication.class, args); } //access command line arguments @Override public void run(String… args) throws Exception { //do something } } 1. …

Read more

Spring Boot JDBC + MySQL + HikariCP example

In this article, we will show you how to create a Spring Boot JDBC application + MySQL and HikariCP. Tools used in this article : Spring Boot 1.5.1.RELEASE MySQL 5.7.x HikariCP 2.6 Maven Java 8 Note Related – Spring Boot JDBC + Oracle database + Commons DBCP2 example 1. Project Structure A standard Maven project …

Read more

How to stop logback status INFO at the start of every log?

The logbook will output its own status (INFO or WARN) at the start of the program, it’s really annoying! 15:34:46,181 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback.groovy] 15:34:46,181 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback-test.xml] 15:34:46,181 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Found resource [logback.xml] at [file:/E:/spring-boot-simple/target/classes/logback.xml] 15:34:46,247 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction – debug …

Read more

How to Stop WordPress Pingbacks and Trackbacks Spam

Review my WordPress wp_comments table and find out the file size is containing 500MB++ for around 1 millions++ comments! Dig inside and find out around 900k++ comments was marked as ‘trackback‘ and it linked back to a spammer’s website. The worst is the this type of ‘trackback‘ comments are kept increasing every second! Follow the …

Read more

VirtualBox – Ubuntu slow and laggy UI

To solve the Ubuntu UI slow performance issue on VirtualBox, increase the “Video Memory” and “Enable 3D Acceleration” Environment VirtualBox 5.1.14 Ubuntu 16 Solution 1. Shutdown VM, clicks “Settings” 2. Display –>> Screen tab –>> Increase the “Video Memory” to Max, and checked the “Enable 3D Acceleration” Done. References What is ‘Ubuntu Unity’ (for the …

Read more

VirtualBox – No backlight on CMSTORM keyboard

This article shows you how to enable the backlight feature (Screen Lock key) on a CMSTORM keyboard. Environment VirtualBox 5.1.14 Ubuntu 16 1. Solution – Quick To fix it quickly, run the following command in a terminal, and press the “Screen Lock key” again, the backlight should be enabled. Terminal $ xmodmap -e ‘add mod3 …

Read more

VirtualBox – Copy and Paste between host and guest machine

By default, the copy and paste between host and guest machine is disabled, To enable it, update “Shared Clipboard” to “Bidirectinal“. 1. Steps to enable Copy and Paste 1.1 Shutdown the VM, in VirtualBox Manager, clicks “Settings” 1.2 General –>> Advanced Tab, update the “Shared Clipboard” to “Bidirectinal”. 1.3 Start the VM, the copy and …

Read more

Spring REST API Validation

In Spring MVC, just annotate a @Valid on the @RequestBody to fire the validation process. Note For complete source code, please refer to this – Spring Boot Ajax example P.S Tested with Spring Boot 1.5.1.RELEASE (Spring 4.3.6.RELEASE) 1. JSR 303 Validation Add JSR303 annotations on a bean. package com.mkyong.model; import org.hibernate.validator.constraints.NotBlank; public class SearchCriteria { …

Read more

Spring Boot Ajax example

This article will show you how to use jQuery.ajax to send a HTML form request to a Spring REST API and return a JSON response. Tools used : Spring Boot 1.5.1.RELEASE Spring 4.3.6.RELEASE Maven 3 jQuery Bootstrap 3 Note You may interest at this classic Spring MVC Ajax example 1. Project Structure A standard Maven …

Read more

jQuery Ajax submit a multipart form

A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax() 1. HTML A HTML form for multiple file uploads and an extra field. <!DOCTYPE html> <html> <body> <h1>jQuery Ajax submit Multipart form</h1> <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> <input type="text" name="extraField"/><br/><br/> <input type="file" name="files"/><br/><br/> <input type="file" name="files"/><br/><br/> <input …

Read more

cURL – POST request examples

Some cURL POST request examples for self reference. 1. Normal POST 1.1 To POST without data. $ curl -X POST http://localhost:8080/api/login/ 1.2 To POST with data. $ curl -d "username=mkyong&password=abc" http://localhost:8080/api/login/ 1.3 Spring REST to accept normal POST data. @PostMapping("/api/login") public ResponseEntity<?> login(@RequestParam("username") String username, @RequestParam("password") String password) { //… } @PostMapping("/api/login") public ResponseEntity<?> login(@ModelAttribute …

Read more

cURL – Post JSON data to Spring REST

This article shows you how to use cURL command to POST JSON data to a Spring REST API. 1. Spring REST A Simple Spring REST API to validate a login. LoginController.java package com.mkyong.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class LoginController { private final Logger …

Read more

Spring Boot file upload example – Ajax and REST

This article shows you how to upload files in Spring Boot web application (REST structure), using Ajax requests. Tools used in this article : Spring Boot 1.4.3.RELEASE Spring 4.3.5.RELEASE Thymeleaf jQuery (webjars) Maven Embedded Tomcat 8.5.6 Google Chrome Browser (Network Inspect) 1. Project Structure A standard Maven project structure. 2. Project Dependency Declares an extra …

Read more

Spring @ExceptionHandler and RedirectAttributes

Since Spring 4.3.5 and 5.0 M4, it supports RedirectAttributes argument in the @ExceptionHandler method. @ExceptionHandler(MyCustomException.class) public String handleError1(MyCustomException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", "abcdefg"); return "redirect:/viewName"; } @ExceptionHandler(MultipartException.class) public String handleError2(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/viewName"; } P.S Read this SPR-14651 Noted If you are using Spring < 4.3.5, do not add ...

Read more

Oracle PL/SQL – After DELETE Trigger example

This article shows you how to use AFTER DELETE TRIGGER, it will fire after the delete operation is executed. In real life scenarios, it is mostly used for purposes like: Auditing or logging 1. After DELETE Trigger In this example, if the user deleted a row of medical_bills, the deleted row will be inserted into …

Read more

Spring Boot – Configure maxSwallowSize in embedded Tomcat

In Spring Boot, you can’t configure the embedded Tomcat maxSwallowSize via the common application properties, there is no option like server.tomcat.*.maxSwallowSize Solution To fix it, you need to declare a TomcatEmbeddedServletContainerFactory bean and configure the maxSwallowSize like this : //… import org.apache.coyote.http11.AbstractHttp11Protocol; import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; private int maxUploadSizeInMb = 10 * 1024 * 1024; …

Read more

Eclipse – How to know this class belongs to which JAR

For example, I want to know this SpringBootApplication class belongs to which JAR or dependency : import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootWebApplication { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootWebApplication.class, args); } } Solution In Eclipse IDE, double clicks on the class name, press CTRL + SHIFT + T (win/*nix) or …

Read more

IntelliJ IDEA – How to know this class belongs to which JAR

For example, how to find out this FileUploadBase class belongs to which JAR or dependency? //… import org.apache.tomcat.util.http.fileupload.FileUploadBase; @ExceptionHandler(FileUploadBase.FileSizeLimitExceededException.class) public String handleError3(Exception e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/uploadStatus"; } Solution In IntelliJ IDEA, double clicks on the class name and press CTRL + n (win/*nix) or CMD + n (mac) to prompt out …

Read more

Spring Boot file upload example

This article shows you how to upload a file in Spring Boot web application. Tools used : Spring Boot 1.4.3.RELEASE Spring 4.3.5.RELEASE Thymeleaf Maven Embedded Tomcat 8.5.6 1. Project Structure A standard project structure. 2. Project Dependency Spring boot dependencies, no need extra library for file upload. pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong</groupId> …

Read more

Java RMI – Distributed objects example

Image Source: Wikimedia.org In Java RMI Hello World example we introduced the Java Remote Method Invocation with a very basic String-based communication between Server-Client. In this example we will take it one small step further and introduce Server-Client communication using Distributed Objects. 1. The Remote Interface First we will develop the Remote Interface which contains …

Read more