Spring JdbcTemplate Handle Large ResultSet

Spring JdbcTemplate example to get a large ResultSet and process it. P.S Tested with Java 8 and Spring JDBC 5.1.4.RELEASE 1. Get large ResultSet 1.1 Below is a classic findAll to get all data from a table. BookRepository.java public List<Book> findAll() { return jdbcTemplate.query( "select * from books", (rs, rowNum) -> new Book( rs.getLong("id"), rs.getString("name"), …

Read more

Spring – Read file from resources folder

In Spring, we can use ClassPathResource or ResourceLoader to get files from classpath easily. P.S Tested with Spring 5.1.4.RELEASE 1. src/main/resources/ For example, an image file in the src/main/resources/ folder 2. ClassPathResource import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import java.io.File; import java.io.InputStream; Resource resource = new ClassPathResource("android.png"); InputStream input = resource.getInputStream(); File file = resource.getFile(); 3. ResourceLoader …

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

Spring MVC – How to handle max upload size exceeded exception

In Spring, you can declare a @ControllerAdvice to catch the ugly max upload size exceeded exception like this : Solution Depends the types of multipartResolver : StandardServletMultipartResolver – catch MultipartException, refer to this example. CommonsMultipartResolver – catch MaxUploadSizeExceededException – refer to this example. GlobalExceptionHandler.java package com.mkyong.exception; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartException; import …

Read more

Spring MVC file upload example – Commons FileUpload

This article will shows you how to use CommonsMultipartResolver to handle file upload in Spring MVC web application. Tools used : Spring 4.3.5.RELEASE commons-fileupload 1.3.2 Maven 3 Tomcat 7 or 8 and Jetty 8, 9 Note For StandardServletMultipartResolver – file upload using Servlet 3.0 multipart request parsing, please refer to this Spring MVC file upload …

Read more

Spring file upload and connection reset issue

A Spring servlet initializer to configure the file upload limit, 5mb per file and 10mb per request. MyWebInitializer.java public class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { private int maxUploadSizeInMb = 5 * 1024 * 1024; // 5 MB //… @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { // upload temp file will put here File uploadDirectory = new File(System.getProperty("java.io.tmpdir")); …

Read more

Spring – Inject value into static variables

Spring doesn’t allow to inject value into static variables, for example: import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GlobalValue { @Value("${mongodb.db}") public static String DATABASE; } If you print out the GlobalValue.DATABASE, a null will be displayed. GlobalValue.DATABASE = null Solution To fix it, create a “none static setter” to assign the injected value for …

Read more

Spring – Mixing XML and JavaConfig

Spring examples to show you how to mix both Spring XML and JavaConfig together. 1. Load JavaConfig From Spring XML A Spring MVC example, uses @Configuration to load everything, and you want integrate with web.xml SpringWebConfig.java package com.mkyong.form.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc …

Read more

Spring embedded database examples

In this tutorial, we will show you a few examples to configure the embedded database engines like HSQL, H2 and Derby in Spring framework. Technologies used : Spring 4.1.6.RELEASE jUnit 4.1.2 Maven 3 Embedded databases tested : HSQLDB 2.3.2 H2 1.4.187 Derby 10.11.1.1 The embedded database concept is very helpful during the development phase, because …

Read more

Spring MethodInvokingFactoryBean Example

In Spring, you can use MethodInvokingFactoryBean to run a method, get the result and inject the result into another bean. This method invoker is very useful in XML configuration, but less use now in favor of annotation and Spring expression. 1. MethodInvokingFactoryBean 1.1 Example to get the current Java version. Spring XML Configuration <!– 1. …

Read more

Spring – View content of HSQLDB embedded database

A Spring @Configuration example to start an HSQLDB embedded database or in-memory database. DataSourceConfig.java package com.mkyong.config.db; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; @Configuration public class DataSourceConfig { @Bean public DataSource dataSource(){ //jdbc:hsqldb:mem:testdb EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) .addScript("db/hsqldb/db.sql") .build(); return db; } } Review the …

Read more

Spring @Value – Import a list from properties file

In this tutorial, we will show you how to import a “List” from a properties file, via Spring EL @Value Tested with : Spring 4.0.6 JDK 1.7 Spring @Value and List In Spring @Value, you can use the split() method to inject the ‘List” in one line. config.properties server.name=hydra,zeus server.id=100,102,103 AppConfigTest.java package com.mkyong.analyzer.test; import java.util.List; …

Read more

Spring @PropertySource example

Spring default loads application.properties into the application’s environment, and we can use @PropertySource to load custom .properties files. file.properties file.path=/server1/file/path Application.java @Configuration @PropertySource("classpath:file.properties") public class Application { @Value("${file.path}") private String path; //… } Table of contents: 1. Project Structure 2. Properties Files 3. @PropertySource and @Value 4. Loads property files from multiple sources 5. Placeholder …

Read more

Spring – ${} is not working in @Value

A simple Spring @PropertySource example to read a properties file. db.properties db.driver=oracle.jdbc.driver.OracleDriver AppConfig.java @Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver; But the property placeholder ${} is unable to resolve in @Value, if print out the driver variable, it will display string ${db.driver} directly, instead of “oracle.jdbc.driver.OracleDriver”. Solution To resolve ${} in Spring …

Read more

Spring Profiles example

Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment. In this tutorial, we will show you a Spring @Profile application, which does …

Read more

Spring Caching and Ehcache example

In this tutorial, we will show you how to enable data caching in a Spring application, and integrate with the popular Ehcache framework. Tools used Ehcache 2.9 Spring 4.1.4.RELEASE Logback 1.0.13 Maven 3 / Gradle 2 JDK 1.7 Eclipse 4.4 Note Spring supports caching since version 3.1 Spring cache has been significantly improved since version …

Read more

ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException

Spring + Hibernate4 integration, and transaction are managed by Spring AOP, example : spring-hibernate.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="userDaoPointCut" expression="execution(* com.mkyong.users.service.*Dao.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="userDaoPointCut" /> …

Read more

Spring + Hibernate : No Session found for current thread

Integrates Spring 3 and Hibernate 4, the system shows the following message while performing database operation : org.hibernate.HibernateException: No Session found for current thread The sessionFactory is injected like this : spring-hibernate4.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" …

Read more

How to autowire DataSource in JdbcDaoSupport

A Simple DAO class extends JdbcDaoSupport, but, unable to inject or @autowired a “dataSource”, the method setDataSource is final, can’t override. UserDetailsDaoImpl.java package com.mkyong.users.dao; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; @Repository public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao { //Error, cannot override the final method from JdbcDaoSupport @Autowired public void setDataSource(DataSource dataSource) { …

Read more

JdbcTemplate queryForInt() is Deprecated

Upgrading Spring version and noticed that queryForInt() is deprecated, what should be replaced by? private boolean isUserExists(String username) { String sql = "SELECT count(*) FROM USERS WHERE username = ?"; boolean result = false; //The method queryForInt(String, Object…) from the type JdbcTemplate is deprecated int count = getJdbcTemplate().queryForInt(sql, new Object[] { username }); if (count …

Read more

queryForObject() throws EmptyResultDataAccessException when record not found

Reviewing a legacy project, and found this Spring JDBC code snippets : public User getUser(String username) { String sql = "SELECT * FROM USER WHERE username = ?"; return getJdbcTemplate().queryForObject( sql, new Object[] { username }, new RowMapper<UserAttempts>() { public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); …

Read more

Spring and Java Thread example

Here are 3 examples to show you how to do “threading” in Spring. See the code for self-explanatory. 1. Spring + Java Threads example Create a simple Java thread by extending Thread, and managed by Spring’s container via @Component. The bean scope must be “prototype“, so that each request will return a new instance, to …

Read more

How to inject null value in Spring

In Spring, you can uses this special <null /> tag to pass a “null” value into constructor argument or property. 1. Constructor Argument The wrong way to inject a null into constructor argument, a really common mistake, and nice try 🙂 <bean id="defaultMongoTypeMapper1" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> <constructor-arg name="typeKey" value="null" /> </bean> Correct way. <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> <constructor-arg …

Read more

IncompatibleClassChangeError : JobDetailBean has interface org.quartz.JobDetail as super class

Developing Quartz 2.1.5 + Spring 3.1.2.RELEASE, hits following error messages : Caused by: java.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.JobDetailBean has interface org.quartz.JobDetail as super class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631) at java.lang.ClassLoader.defineClass(ClassLoader.java:615) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2901) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1170) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556) at org.springframework.util.ClassUtils.forName(ClassUtils.java:258) … 19 more Solution Quartz 2 APIs are changed a lot, and someone already …

Read more

java.lang.ClassNotFoundException: org.springframework.transaction.TransactionException

Developing Quartz with Spring 3, and hits following error message. Caused by: java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionException at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) ….. Caused by: java.lang.ClassNotFoundException: org.springframework.transaction.TransactionException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556) … 29 more Solution Doesn’t matter with Quartz, above error message show that you need Spring transaction dependency. To fix it, just include …

Read more

Spring request scope error : No thread-bound request found

Problem Developing web application with Spring, make a bean with scope of “request“. @Component @Scope("request") public class PaymentService { @Autowired UserBo userBo; //… But hit following error message? Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally …

Read more

Spring Autowiring @Qualifier example

In Spring, @Qualifier means, which bean is qualify to autowired on a field. See following scenario : Autowiring Example See below example, it will autowired a “person” bean into customer’s person property. package com.mkyong.common; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Customer { @Autowired private Person person; //… } But, two similar beans “com.mkyong.common.Person” are declared …

Read more

Spring Autowiring by AutoDetect

In Spring, “Autowiring by AutoDetect“, means chooses “autowire by constructor” if default constructor (argument with any data type), otherwise uses “autowire by type“. See an example of Spring “auto wiring by autodetect”. Auto wiring the “kungfu” bean into “panda”, via constructor or type (base on the implementation of panda bean). <bean id="panda" class="com.mkyong.common.Panda" autowire="autodetect" /> …

Read more

Spring Autowiring by Constructor

In Spring, “Autowiring by Constructor” is actually autowiring by Type in constructor argument. It means, if data type of a bean is same as the data type of other bean constructor argument, auto wire it. See a full example of Spring auto wiring by constructor. 1. Beans Two beans, developer and language. package com.mkyong.common; public …

Read more

Spring DI via constructor

Uses Spring to dependency inject a bean via constructor. 1. IOutputGenerator An interface and implementation class of it. package com.mkyong.output; public interface IOutputGenerator { public void generateOutput(); } package com.mkyong.output.impl; import com.mkyong.output.IOutputGenerator; public class JsonOutputGenerator implements IOutputGenerator { public void generateOutput(){ System.out.println("This is Json Output Generator"); } } 2. Helper class A helper class, later …

Read more

Spring Autowiring by Type

In Spring, “Autowiring by Type” means, if data type of a bean is compatible with the data type of other bean property, auto wire it. For example, a “person” bean exposes a property with data type of “ability” class, Spring will find the bean with same data type of class “ability” and wire it automatically. …

Read more

Spring Autowiring by Name

In Spring, “Autowiring by Name” means, if the name of a bean is same as the name of other bean property, auto wire it. For example, if a “customer” bean exposes an “address” property, Spring will find the “address” bean in current container and wire it automatically. And if no matching found, just do nothing. …

Read more

Spring DI via setter method

A simple Spring example to show you how to dependency inject a bean via setter method, the most common used DI method. 1. IOutputGenerator An interface and implemntation class of it. package com.mkyong.output; public interface IOutputGenerator { public void generateOutput(); } package com.mkyong.output.impl; import com.mkyong.output.IOutputGenerator; public class CsvOutputGenerator implements IOutputGenerator { public void generateOutput() { …

Read more

Spring AOP transaction management in Hibernate

Transaction management is required to ensure the data integrity and consistency in database. Spring’s AOP technique is allow developers to manage the transaction declarative. Here’s an example to show how to manage the Hibernate transaction with Spring AOP. P.S Many Hibernate and Spring configuration files are hidden, only some important files are shown, if you …

Read more

Spring + JDK Timer scheduler example

Note Learn the JDK Timer scheduler example without Spring and compare the different with this example. In this example, you will use Spring’s Scheduler API to schedule a task. 1. Scheduler Task Create a scheduler task… package com.mkyong.common; public class RunMeTask { public void printMe() { System.out.println("Run Me ~"); } } <bean id="runMeTask" class="com.mkyong.common.RunMeTask" /> …

Read more

Maven + (Spring + Hibernate) Annotation + MySql Example

Download It – Spring-Hibernate-Annotation-Example.zip In last tutorial, you use Maven to create a simple Java project structure, and demonstrate how to use Hibernate in Spring framework to do the data manipulation works(insert, select, update and delete) in MySQL database. In this tutorial, you will learn how to do the same thing in Spring and Hibernate …

Read more

Spring Resource loader with getResource() example

Spring’s resource loader provides a very generic getResource() method to get the resources like (text file, media file, image file…) from file system , classpath or URL. You can get the getResource() method from the application context. Here’s an example to show how to use getResource() to load a text file from 1. File system …

Read more