Mocking Spring Data DateTimeProvider

In this article, we will demonstrate an integration test where we have to persist the entities with mocked auditing date fields when JPA Auditing is enabled. Technologies used: Spring Boot 2.4.0 Spring 5.3.1 JUnit Jupiter 5.7.0 Tomcat embed 9.0.39 Java 8 1. Project Dependencies pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> …

Read more

Spring Boot + Spring Data JPA + PostgreSQL example

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

Read more

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

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

Spring Boot + Spring Data + Elasticsearch example

In this article, we will discuss about “How to create a Spring Boot + Spring Data + Elasticsearch Example”. Tools used in this article : Spring Boot 1.5.1.RELEASE Spring Boot Starter Data Elasticsearch 1.5.1.RELEASE Spring Data Elasticsearch 2.10.RELEASE Elasticsearch 2.4.4 Maven Java 8 Note SpringBoot 1.5.1.RELEASE and Spring Data Elasticsearch 2.10.RELEASE supports only ElasticSearch 2.4.0. …

Read more

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

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

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

Spring Data MongoDB + JSR-310 or Java 8 new Date APIs

While saving an object containing the new Java 8 java.time.LocalDateTime, the following error is thrown : org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.time.LocalDateTime] to type [java.util.Date] Tested Spring 4.3.2.RELEASE Spring Data MongoDB 1.9.2.RELEASE Is Spring-data supporting the new Java 8 Date APIs (JSR-310)? 1. Spring Data + JSR-310 Yes, Spring-data supports the …

Read more

Spring Data MongoDB – Aggregation Grouping Example

In this tutorial, we will show you how to do the data grouping with Spring Data + MongoDB aggregation framework. 1. Test Data domain.json { "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" } { "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"} { "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" …

Read more

Spring Data MongoDB – Select fields to return

In MongoDB console, you can use field:1 to select the fields to return from a query : > db.hosting.find({},{domain:1, count:1}); In Spring Data for MongoDB, you use query.fields().include : HostingDaoImpl.java package com.mkyong.core.hosting.dao; import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; import com.hostingcompass.core.db.dao.MongoDaoImpl; @Repository public class HostingDaoImpl extends MongoDaoImpl<Hosting> implements HostingDao { …

Read more

Spring Data MongoDB : get last modified records (date sorting)

In Mongodb, you can use sort()to do the date sorting. 1. MongoDB Sorting Examples In Mongodb, to sort a “date” field, issues : //The ‘1’ = sort ascending (oldest to newest) db.domain.find().sort({lastModifiedDate:1}) { "_id" : 1, "lastModifiedDate" : ISODate("2013-08-13T07:18:04.774Z") } { "_id" : 2, "lastModifiedDate" : ISODate("2013-09-03T08:12:16.309Z") } { "_id" : 3, "lastModifiedDate" : ISODate("2013-10-03T08:12:16.309Z") …

Read more

Spring Data MongoDB : like query example

In SQL, the ‘like’ query is looks like this : select * from tags where tagName like ‘%apple%’ In MongoDB console, it looks like this : db.tags.find({"tagName": /apple/}) In Spring data mongodb, it implements with Criteria or BasicQuery : String tagName = "apple"; Query query = new Query(); query.limit(10); query.addCriteria(Criteria.where("tagName").regex(tagName)); mongoOperation.find(query, Tags.class); String tagName = …

Read more

Spring asm dependency issue in Spring Data

Using Spring Data MongoDB 1.2.1.RELEASE and Spring core 3.2.2.RELEASE, while system is starting, it hits some weird spring-asm IncompatibleClassChangeError errors : java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <springdata.version>1.2.1.RELEASE</springdata.version> </properties> <dependencies> <!– Spring Core –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!– Spring Data for MongoDB –> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>${springdata.version}</version> …

Read more

Spring Data MongoDB : Save binary file, GridFS example

In MongoDB, you can use GridFS to store binary files. In this tutorial, we show you how to use Spring Data’s GridFsTemplate to store / read image in / from MongoDB. 1. GridFS – Save example (Spring config in Annotation) Gat an image file and save it into MongoDB. SpringMongoConfig.java package com.mkyong.config; import org.springframework.context.annotation.Bean; import …

Read more

Due to limitations of the BasicDBObject, you can’t add a second ‘$and’

Problem Using Spring data and Mongodb, below is a function to find data within a date range. public List<RequestAudit> findByIpAndDate(String ip, Date startDate, Date endDate) { Query query = new Query( Criteria.where("ip").is(ip) .andOperator(Criteria.where("createdDate").gte(startDate)) .andOperator(Criteria.where("createdDate").lt(endDate)) ); return mongoOperation.find(query, RequestAudit.class); } It hits following error message : org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDBObject, you can’t add …

Read more

Spring Data MongoDB remove _class column

By default, SpringData’s MappingMongoConverter add an extra “_class” column for every object saved in MongoDB. For example, public class User { String username; String password; //…getters and setters } Save it MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate"); User user = new User("mkyong", "password123"); mongoOperation.save(user, "users"); Result > db.users.find() { "_class" : "com.mkyong.user.User", "_id" : ObjectId("5050aef830041f24ff2bd16e"), "password" : …

Read more

Spring Data MongoDB : Delete document

In Spring data for MongoDB, you can use remove() and findAndRemove() to delete documents from MongoDB. remove() – delete single or multiple documents. findAndRemove() – delete single document, and returns the deleted document. Common Mistake Don’t use findAndRemove() to perform a batch delete (remove multiple documents), only the first document that matches the query will …

Read more

Spring Data MongoDB : Update document

In Spring data – MongoDB, you can use following methods to update documents. save – Update the whole object, if “_id” is present, perform an update, else insert it. updateFirst – Updates the first document that matches the query. updateMulti – Updates all documents that match the query. Upserting – If no document that matches …

Read more

Spring Data MongoDB : Insert document

In Spring data MongoDB, you can use save(), insert() to save a or a list of objects into mongoDB database. User user = new User("…"); //save user object into "user" collection / table //class name will be used as collection name mongoOperation.save(user); //save user object into "tableA" collection mongoOperation.save(user,"tableA"); //insert user object into "user" collection …

Read more

Spring Data MongoDB hello world example

In this tutorial, we show you how to use “SpringData for MongoDB” framework, to perform CRUD operations in MongoDB, via Spring’s annotation and XML schema. Updated on 1/04/2013 Article is updated to use latest SpringData v 1.2.0.RELEASE, it was v1.0.0.M2. Tools and technologies used : Spring Data MongoDB – 1.2.0.RELEASE Spring Core – 3.2.2.RELEASE Java …

Read more