,

Introduction

I’m quickly becoming a fan of using CircleCI for CI builds. I’m finding that CircleCI is a very powerful platform. Recently, I configured CircleCI to build a Spring Boot Microservice. The microservice was generated by JHipster.

CircleCI is a online resource which uses Docker containers to run your CI builds. Since your build is running inside a Docker container, you can customize the container to support numerous different scenarios.

In this post, we’ll look at configuring CircleCI to build a Spring Boot Microservice generated by JHipster

Using CircleCI

CircleCI Account

CircleCI has a free tier which you can use for your CI builds. The free tier is limited to one running container at a time. Which is fine for many situations.

Signing up for CircleCI is crazy easy. All you need is a GitHub, BitBucket, or Google account.

Click here to get your free account.

Configuring CircleCI to Build JHipster Projects

JHipster Microservice

In this example, I’m using a Spring Boot microservice generated by JHipster.

My example application is a VERY basic example. I have not added any domains.

The focus of this post is on CI builds, not building microservices.

You can get the complete source code for this blog post here on GitHub.

CircleCI Build Config File

To build your project, CircleCI will look in the project root for the directory .circleci. The CircleCI build file is a YAML file named config.yml .

CircleCI has very powerful build capabilities. I cannot cove everything in this post. But, you can Click here to explore the capabilities found in CircleCI 2.0.

As Spring Framework Developers, it’s likely we will be using Maven or Gradle for our build tools. (I hope none of you are using Ant!)

Below are example build files for Maven and Gradle provided by CircleCI.

Maven CircleCI config.yml Example

Gradle CircleCI config.yml Example

Installing NodeJS

If your JHipster project has a UI component, you will need to install NodeJS and Yarn for the build process.

Adding these commands to the ‘steps’ section of your CircleCI build configuration will install NodeJS into the docker container running your build.

Installing Yarn

JHipster also uses Yarn for dependency management of UI components.

You can install Yarn by adding the following steps to your CircleCI build configuration.

Custom Docker Images

CircleCI does provide a number of pre-built images you can use for your builds.

In this example, I’m using an image with Java pre-installed.

It does not have NodeJS or Yarn pre-installed.

Above, I’m showing you how to install NodeJS and Yarn into your build container.

If I needed to build a lot of JHipster projects, I probably would develop my own custom Docker image for the builds.

In my custom image, I would pre-install NodeJS and Yarn.

Comment below if you would like to see a future blog post on how to setup a custom Docker image like this!

Building A Docker Image with CircleCI

You can also use CircleCI to build docker images to hold your Spring Boot microservice.

Of course, JHipster out of the box gives us the tools to build the Docker image.

CircleCI gives us the ability to leverage a remote Docker service to support Docker commands from within our build container.

To build a Docker Image of our Spring Boot microservice, we need to add two steps to our build configuration.

  1. Setup the Remote Docker connection to our build container.
  2. Run the build command for Maven / Gradle to build the Docker Image.

Here is an example configuration for using Gradle to create the Docker Image:

Complete CircleCI Build File

Here is the complete CircleCI Build file for my Spring Boot Microservice.

.circleci/config.yml

Memory Errors in CircleCI

In setting up some of my builds for JHipster, I ran into a intermittent build failures.

Here is the error I was seeing:

The exit value of 137 indicates the Java process was getting terminated by the operating system. Effectively the JVM was consuming too much memory. Then Docker was killing the container.

Some builds would work, some would fail.

I worked on this issue several hours and learned a lot about Gradle and JVM memory management.

Gradle Daemon for CI Builds

For CI Builds, the Gradle team recommends disabling the Gradle daemon. You can do this as follows:

gradle.properites

JVM Memory Settings

You can also configure JVM memory settings via the Gradle properties file.

The above configuration did not help me.

Gradle seems to be launching another JVM process to execute tests in, and that JVM process does not seem to honor the memory arguments set in org.gradle.jvmargs or via environment variables.

However, what did work for me, was to configure the test task via build.gradle.

I added the following to the build configuration generated by JHipster:

build.gradle

Note: MaxPermSize has been deprecated from Java 8 and above. See this link.

Once I limited the JVM memory consumption, my builds became stable.

The JVM was likely failing due to how Java works with Docker. The JVM ‘sees’ memory for the entire host system, and does not recognize the memory limitations of the Docker container. See this post for additional details.

This issue is going to get better in future releases of Java. It has been addressed in Java 9 and backported to Java 8.

 

0
Share
,

In this tutorial, we will be building a demo web application for a Dog Rescue organization that uses JdbcTemplate and Thymeleaf. For this example, we will be using a MySQL database. However, this example is not limited to MySQL and the database could be swapped out for another type with ease.

You can browse and download the code on Github as you follow this example.

1 – Project Structure

The project uses a typical Maven structure. You may notice I am using Spring Tool Suite, which JT is not a fan of!

Project structure of Spring Boot Thymeleaf JdbcTemplate tutorial

 

2 – Dependencies

Besides typical Spring Boot Starter dependencies, we include Thymeleaf and MySQL connector.

 

3 – Configuration

We configure all our datasource information here in the application.properties. Later we will autowire this for our JdbcTemplate use.

application.properties

4 – Database Initialization

When our application starts, these SQL file will be automatically detected and ran. In our case, we will drop the table “dog” every time the application starts, create a new table named “dog” and then insert the values shown in data.sql.

You may recall that “vaccinated” is a Boolean value in Java. In MySQL Boolean is a synonym for TINYINT(1), so we can use this data type for the column.

schema.sql

data.sql

5 – Model/Entity

Here we define the characteristics of a dog that we want to know for our Dog Rescue. The getters and setters were auto created and it is suggested to do this to save time.

6 – Repository

We extend the CrudRepository for our DogRepository. The only additional method we create is a derived query for finding a dog by name.

7 – Service

Using the SOLID principles that JT discusses on the site here :SOLID Principles , we build a service interface and then implement that interface.

DogService.java

DogServiceImpl.java

Here we implement the methods mentioned in DogService.java.

  • addADog – is an example of how to add a record using JdbcTemplate’s update method. It takes three parameters: String, Date and Boolean.
  • deleteADOG – is an example of how to delete a record using JdbcTemplate’s update method. It takes two parameters: Long (id) and String (name).
  • List atriskdogs – is an example of how to select records using JdbcTemplate’s query method. This uses a
    ResultSetExtractor. It takes one parameter: Date. The method returns records of dogs that were rescued before that date that have not been vaccinated (Boolean value of false).
  • long getGeneratedKey – is an example of how to insert records using JdbcTemplate’s query method with PreparedStatementCreator and retrieve a generated key. It takes the same parameters as the other insert example: String, Date and Boolean.

8 – Controller

DogController.java

    • @GetMapping(value = “/”) – there is an optional requirement to provide a search value of type Date in yyyy-MM-dd format. This variable is called q (for “query”) and if it is not null then we will create an ArrayList of all dogs rescued before that date who have not been vaccinated. This ArrayList is called dogModelList and added as an attribute known as “search”. This attribute will be used in our Thymeleaf template.
      Because of its ease of use,
      we use the built in findall method of the CrudRepository to create a list of all dogs in the repository and add it as an attribute, which will also be used by Thymeleaf.
    • @PostMapping(value = “/”) – we request all the parameters that will be passed in our HTML form. We use these values to add a dog to our database.
    • @PostMapping(value = “/delete”) – we request the parameters needed to delete a dog. After the dog is deleted, we redirect the user back to our homepage.
    • @PostMapping(value = “/genkey”) – this is the mapping for inserting a record that returns a generated key. The generated key is printed to standard out in our example.

9 – Thymeleaf template

As this is a basic example application to demonstrate approaches to JdbcTemplate, JPA, Thymeleaf, and other technologies, we have just this one page with a minimalist user interface.

      • Using th:each we are able to iterate through all the records in our dog table
      • Using th:text with the variable and field name, we can display the record. I.E. th:text=”${dogs.id}
      • Using th:if=”${not #lists.isEmpty(search), we prevent the web page from showing the table of search results for dogs at risk (not vaccinated) unless there are results to be shown.
      • With our forms, we map the request to a specific URI and specify names for the inputs of our form that match the parameters in our controller.

index.html

10 – @SpringBootApplication

Our class with the main method has nothing unique in it. The @SpringBootApplication annotation takes care of autodetecting beans that are registered with the various stereotype annotations, such as @Service, etc.

11 – Demo

Landing page

So, I have navigated to localhost:8080 as I did not change the default ports for this application. When I land on the page, you can see that it is displaying the current dogs in our database.

Dog Rescue homepage

Find Dogs That Need Vaccines

Imagine that instead of three dogs in this database we had a larger, less manageable number. Having a feature that allows employees of a dog rescue to find dogs that need vaccinations would be useful if there were more dogs.

The search functionality takes a date and shows dogs that were rescued before that date that have not been vaccinated.

Although we know right now that Buddy is the only dog without his vaccinations, let’s show how this works.

Search for dogs without vaccine

Thymeleaf conditional statement

Add A Dog

As we know, the ID is autogenerated. So we can add all the fields minus the ID and successfully still a Dog to the database.
Adding a dog in thymeleaf template

Table in thymeleaf

Delete A Dog

We remove a dog from the database by using the primary ID but also ask for the name of the dog to verify it is the correct one.

We redirect the user back to the index, so it displays the table of dogs minus the one deleted. Below you can see I have removed “Pooch”.
Delete JdbcTemplate Thymeleaf

Spring Boot Delete Dog

Add A Dog And Retrieve Generated Key

Sometimes we need to retrieve the generated key from our database for other uses. Here in this example, we insert a dog named “Lassie” and retrieve the generated key.

Insert Lassie in database

In the console, this is printed

Our table is once again updated

updated table

Download the code from Github

If you’d like, you can view and download the code from Github

About Michael

Michael Good is a software engineer located in the Washington DC area that is interested in Java, cyber security, and open source technologies. Follow his personal blog to read more from Michael.

0
Share
,

Spring Data MongoDB has been updated to leverage the reactive programming model introduced in Spring Framework 5. This was followed by support for reactive data access for NoSQL databases, such as MongoDB, Cassandra, and Redis.

With the rise in popularity of NoSQL databases, MongoDB has rapidly gained popularity in the enterprise and the Spring community.

I have published both a post and a video for setting up MongoDB within a Spring Boot application.

In this post, we’ll take a look at using the reactive programming features in Spring Framework 5 and Spring Data MongoDB.

If you’re new to Reactive programming, I’ll suggest you first go through What are Reactive Streams in Java? post, followed by the Spring Web Reactive post.

The Maven POM

For this post, I’m using Embedded MongoDB. I want the benefit of talking to an instance loaded in memory with the same capabilities as my production environment. This makes development and testing blazing fast.

You can check my post to configure and use Embedded MongoDB in a Spring Boot application here.

The dependency to bring in the Embedded MongoDB is this.

The whole capability of Reactive MongoDB lies on the MongoDB driver. The official MongoDB Reactive Streams Java Driver implements the Reactive Streams API for interoperability with other reactive stream implementations. The reactive driver provides asynchronous stream processing with non-blocking back pressure for MongoDB.

To use the driver, add this dependency.

Here is the complete pom.xml.

pom.xml

The Domain Object

I have written a Product domain object for this post. Products have a name, description, price, and product URL. 

Product.java

Spring Data MongoDB Reactive CRUD Repository

If you have worked with Spring Data in a Spring Boot application, you are familar with the repository pattern.  You extend CrudRepository or its sub interface, and Spring Data MongoDB will generate the implementation for you.

Reactive repositories work the same way. You extend your repository interface from ReactiveCrudRepository, specify domain-specific query methods, and rely on Spring Data MongoDB to provide the implementations.

ReactiveCrudRepository uses reactive types introduced in Spring Framework 5. These are  Mono and Flux which implement Reactive Streams.

Here is reactive repository interface.

ReactiveProductRepository.java

As you can see, in this ReactiveProductRepository interface, the repository uses reactive types as return types.

Reactive repositories in Spring Data MongoDB can also use reactive types for parameters. The overloaded findByName() and findByNameAndImageUrl() methods are examples of this.

Configuration for Spring Data MongoDB Reactive Repositories

The configuration class is similar to a non-reactive one. Along with some infrastructural setup, we have the @EnableReactiveMongoRepositories annotation that activates support for reactive Spring Data.

The code of the ApplicationConfiguration class is this.

ApplicationConfiguration.java

This ApplicationConfiguration class extends AbstractReactiveMongoConfiguration, the base class for reactive Spring Data MongoDB configuration. The mongoClient() method is annotated with @Bean to explicitly declare a configurable MongoClient bean that represents a pool of connections for MongoDB.

Spring Data MongoDB Integration Tests

Let’s write few integration tests for the repository layer to verify that our code is using reactive MongoDB as expected.

Here is the integration test code:

ReactiveProductRepositoryIntegrationTest.java

In the test class, we autowired in two Spring Beans.

Our ReactiveProductRepository implementation that Spring Data MongoDB provides and a ReactiveMongoOperations implementation.

ReactiveMongoOperations is the interface for the main reactive Template API class, ReactiveMongoTemplate. This interface defines a basic set of reactive data access operations using Project Reactor Mono and Flux reactive types.

ReactiveMongoOperations contains reactive counterpart for most of the operations available in the MongoOperations interface of the traditional blocking template API.

The setup portion of our integration test will drop any existing documents and re-create the Product collection. The setup method then inserts 4 new documents into our MongoDB collection.

We’re calling the .block()  method to ensure processing completes before the next command is executed.

Here is the output of the Integration tests from IntelliJ:

Test Output from Spring Data MongoDB reactive tests

You can get the complete source code for this post here.

0
Share
,

Recently we’ve seen a rise in popularity of NoSQL databases. MongoDB has rapidly gained popularity in the enterprise and the Spring community.

While developing and testing Spring Boot applications with MongoDB as the data store, it is common to use the lightweight Embedded MongoDB rather than running a full-fledged server. As the embedded MongoDB runs in memory, it is blazing fast and will save you lot of time both during development and running your tests, in your development machine or a CI server.

I have covered setting up MongoDB in a Spring Boot application here.

In this post, I’ll discuss how to use embedded MongoDB in a Spring Boot application.

I posted a video here that explains the Spring Boot application that I’ll use in this post.

The Maven POM

Embedded MongoDB downloads and fires-up a real MongoDB instance. You get the benefit of talking to an instance loaded in memory with the same capabilities as your production environment. The Maven POM dependency to include Embedded MongoDB is this:

You also need to include the embedmongo-spring dependency that provides Spring Factory Bean for Embedded MongoDB, like this.

Finally, with this spring-boot-starter-data-mongodb dependency pulled in, you should be all set to use embedded MongoDB in your Spring Boot app.

The complete pom.xml is this.

pom.xml

The MongoDB Config

You need to provide a MongoTemplate bean to SpringBoot for your application to interact with the embedded MongoDB instance. You typically use a @Configuration class, like this.

MongoConfig.java

In this MongoConfig class, EmbeddedMongoFactoryBean is a FactoryBean for Embedded MongoDB that runs MongoDB as a managed process and exposes preconfigured instance of MongoClient.

This is all you need to do to start using Embedded MongoDB in a Spring Boot application.

Note: By default your application will connect to the test database. For a different database, set the spring.data.mongodb.database property in your application.properties configuration file.

You can download the source code from git here.

0
Share

Spring Boot makes developing RESTful services ridiculously easy. And using Swagger makes documenting your RESTful services easy.

Building a back-end API layer introduces a whole new area of challenges that goes beyond implementing just endpoints. You now have clients which will now be using your API. Your clients will need to know how to interact with your API. In SOAP based web services, you had a WSDL to work with. This gave API developers a XML based contract, which defined the API. However, with RESTFul web services, there is no WSDL. Thus your API documentation becomes more critical.

API documentation should be structured so that it’s informative, succinct, and easy to read. But best practices on, how you document your API, its structure, what to include and what not to is altogether a different subject that I won’t be covering here. For best practices on documentation, I suggest going through this presentation of Andy Wikinson.

In this post I’ll cover how to use Swagger 2 to generate REST API documentation for a Spring Boot project.

Swagger 2 in Spring Boot

Swagger 2 is an open source project used to describe and document RESTful APIs. Swagger 2 is language-agnostic and is extensible into new technologies and protocols beyond HTTP. The current version defines a set HTML, JavaScript, and CSS assets to dynamically generate documentation from a Swagger-compliant API. These files are bundled by the Swagger UI project to display the API on browser. Besides rendering documentation, Swagger UI allows other API developers or consumers to interact with the API’s resources without having any of the implementation logic in place.

The Swagger 2 specification, which is known as OpenAPI specification has several implementations. Currently, Springfox that has replaced Swagger-SpringMVC (Swagger 1.2 and older) is popular for Spring Boot applications. Springfox supports both Swagger 1.2 and 2.0.

We will be using Springfox in our project.

To bring it in, we need the following dependency declaration in our Maven POM.

In addition to Sprinfox, we also require Swagger UI. The code to include Swagger UI is this.

Free Spring TutorialThe Spring Boot RESTful Application

Our application implements a set of REST endpoints to manage products. We have a Product JPA entity and a repository named ProductRepository that extends CrudRepository to perform CRUD operations on products against an in-memory H2 database.

The service layer is composed of a ProductService interface and a ProductServiceImpl implementation class.

The Maven POM of the application is this.

pom.xml

The controller of the application , ProductController defines the REST API endpoints. The code of ProductController is this.

In this controller, the @RestController annotation introduced in Spring 4.0 marks ProductController as a REST API controller. Under the hood, @RestController works as a convenient annotation to annotate the class with the @Controller and @ResponseBody.

The @RequestMapping class-level annotation maps requests to /product onto the ProductController class. The method-level @RequestMapping annotations maps web requests to the handler methods of the controller.

Configuring Swagger 2 in the Application

For our application, we will create a Docket bean in a Spring Boot configuration to configure Swagger 2 for the application. A Springfox Docket instance provides the primary API configuration with sensible defaults and convenience methods for configuration. Our Spring Boot configuration class, SwaggerConfig is this.

In this configuration class, the @EnableSwagger2 annotation enables Swagger support in the class. The select() method called on the Docket bean instance returns an ApiSelectorBuilder, which provides the apis() and paths() methods to filter the controllers and methods being documented using String predicates. In the code, the RequestHandlerSelectors.basePackage predicate matches the guru.springframework.controllers base package to filter the API. The regex parameter passed to paths() acts as an additional filter to generate documentation only for the path starting with /product.

At this point, you should be able to test the configuration by starting the app and pointing your browser to http://localhost:8080/v2/api-docs
Swagger JSON Output
Obviously, the above JSON dump that Swagger 2 generates for our endpoints is not something we want.

What we want is some nice human readable structured documentation, and this is where Swagger UI takes over.

On pointing your browser to http://localhost:8080/swagger-ui.html, you will see the generated documentation rendered by Swagger UI, like this.

Swagger default documentation

As you can see, Swagger 2 used sensible defaults to generate documentation of our ProductController .

Then Swagger UI wrapped everything up to provide us an intuitive UI. This was all done automatically. We did not write any code or other documentation to support Swagger.

Customizing Swagger

So far, we’ve been looking at Swagger documentation, as it comes out of the box. But Swagger 2 has some great customization options.

Let’s start customizing Swagger by providing information about our API in the SwaggerConfig class like this.

SwaggerConfig.java

In the SwaggerConfig class, we have added a metaData() method that returns and ApiInfo object initialized with information about our API. Line 23 initializes the Docket with the new information.

The Swagger 2 generated documentation, now look similar to this.
Swagger Generated API Information

Swagger 2 Annotations for REST Endpoints

At this point, if you click the product-controller link, Swagger-UI will display the documentation of our operation endpoints, like this.
Swagger default endpoint documentation

We can use the @Api annotation on our ProductController class to describe our API.

The Swagger-UI generated documentation will reflect the description, and now looks like this.
Customized Swagger Generated API Description
For each of our operation endpoint, we can use the @ApiOperation annotation to describe the endpoint and its response type, like this:

Swagger 2 also allows overriding the default response messages of HTTP methods. You can use the @ApiResponse annotation to document other responses, in addition to the regular HTTP 200 OK, like this.

One undocumented thing that took quite some of my time was related to the value of Response Content Type. Swagger 2 generated "*/*", while I was expecting "application/json" for Response Content Type. It was only after updating the @RequestMapping annotation with produces = "application/json" that the desired value got generated. The annotated ProductController is this.

ProductController.java

The output of the operation endpoints on the browser is this.
Swagger generated endpoint and response code documentation
If you have noticed, the current documentation is missing one thing – documentation of the Product JPA entity. We will generate documentation for our model next.

Swagger 2 Annotations for Model

You can use the @ApiModelProperty annotation to describe the properties of the Product model. With @ApiModelProperty, you can also document a property as required.

The code of our Product class is this.

Product.java

The Swagger 2 generated documentation for Product is this.
Swagger model documentation

Summary

Beside REST API documentation and presentation with Swagger Core and Swagger UI, Swagger 2 has a whole lot of other uses too that is beyond the scope of this post. One of my favorite is Swagger Editor, a tool to design new APIs or edit existing ones. The editor visually renders your Swagger definition and provides real time error-feedback. Another one is Swagger Codegen – a code generation framework for building Client SDKs, servers, and documentation from Swagger definitions.

Swagger 2 also supports Swagger definition through JSON and YAML files. It is something you should try if you want to avoid implementation-specific code in your codebase by externalizing them in JSON and YAML files – something that I will cover in a future post.

The code for this post is available for download here.

5
Share

Out of the box, Spring Boot is very easy to use with the H2 Database. Spring programmers typically prefer writing code against such lightweight in-memory database, rather than on an enterprise database server such as Microsoft SQL Server or Oracle.

In-memory databases come with several restrictions making them useful only in the development stages in local environments. While in-memory databases are great to develop against, data is not persisted to disk, thus is lost when the database is shut down.

As the development progresses, you would most probably require an RDBMS to develop and test your application before deploying it to use a production database server. I have written a series of posts on integrating Spring Boot for Oracle, MySQL, MariaDB, and PostgreSQL.

Spring makes switching between RDBM’s simple. When you’re using Spring Data JPA with an ORM technology such as Hibernate, the persistence layer is nicely well decoupled. Which allows you to easily run your code against multiple databases. The level of decoupling even allows you to easily switch between an RDBMS and a NoSQL database, such as MongoDB. One of my previous post on Integrating Spring Boot for MongoDB covers that.

In this post, I will discuss Spring Boot configuration for Microsoft SQL Server.

SQL Server Configuration

For this post, I’m using SQL Server 2014 Express installed locally on my laptop. I used SQL Server 2014 Management Studio to connect to the database server using SQL Server Authentication.
Connect To SQL Server
Once you are logged in, create a springbootdb database from the Object Explorer window.
Configure SQL Server database for use with Spring Boot

A common problem that trips up many Java developers trying to connect to SQL Server is this error:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: “Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.”.

I too learned the hard way to resolve it with these steps.

    1. From the Start menu, open SQL Server 2014 Configuration Manager.
    2. Click Protocol for SQLEXPRESS under SQL Server Network Configuration on the left pane. On the right pane, right- click TCP/IP, and select Properties.
    3. On the TCP/IP Properties dialog box that appears, click the IP Addresses tab.
    4. Scroll down to locate the IPALL node. Remove any value, if present for TCP Dynamic Ports and specify 1433 for TCP Port.

TCP/IP Properties for SQL Server

  1. Click OK.
  2. Again right-click TCP/IP on the right pane, and select Enable.
  3. On the SQL Server Services node, right-click SQL Server (SQLEXPRESS), and select Restart.

This sets up SQL Server to be reached from JDBC code.

SQL Server Dependencies

To connect with SQL Server from Java applications, Microsoft provides a Microsoft JDBC Driver for SQL Server. However, till November 2016, Maven did not directly support the driver as it was not open sourced. By making it open source, Microsoft finally made the driver available on the Maven Central Repository. More information can be found here.

The Maven POM file of my Spring Boot application that brings in the database driver is this.

pom.xml

Spring Boot Properties

We need to override the H2 database properties being set by default in Spring Boot. The nice part is, Spring Boot sets default database properties only when you don’t. So, when we configure SQL Server for use, Spring Boot won’t setup the H2 database anymore.

The following data source configurations are required to configure SQL Server with Spring Boot.

application.properties

As we are using JPA, we need to configure Hibernate for SQL Server too. Line 7 tells Hibernate to recreate the database on startup. This is definitely not the behavior we want if this was actually a production database You can set this property to the following values: none, validate, update, create-drop.

For a production database, you probably want to use validate.

Free Spring Tutorial
Free Spring Boot Tutorial

JPA Entity

In our example application, we will perform CRUD operations on a user. For that, we will write a simple JPA entity, User for our application. I have written a post to use Spring Data JPA in a Spring Boot Web application, and so won’t go into JPA here.

User.java

JPA Repository

Spring Data JPA CRUD Repository is a feature of Spring Data JPA that I extensively use. Using it, you can just define an interface that extends CrudRepository to manage entities for most common operations, such as saving an entity, updating it, deleting it, or finding it by id. Spring Data JPA uses generics and reflection to generate the concrete implementation of the interface we define.

For our User domain class we can define a Spring Data JPA repository as follows.

UserRepository.java

That’s all we need to setup in Spring Boot to use SQL Server.

Let’s write some test code for this setup.

UserRepositoryTest.java

For the test, I have used JUnit. To know more about JUnit, you can refer my series on JUnit Testing.

The result of the JUnit test is this.

JUnit Test Result for SQL Server

Conclusion

As you can see, it is very easy to configure Spring Boot for SQL Server. As usual, Spring Boot will auto configure sensible defaults for you. And as needed, you can override the default Spring Boot properties for your specific application.

0
Share

When developing enterprise applications, Spring programmers typically prefer writing data-centric code against a lightweight in-memory database, such as H2 rather than running an enterprise database server such as Oracle, or MySQL. Out of the box, Spring Boot is very easy to use with the H2 Database.

In-memory databases are useful in the early development stages in local environments, but they have lots of restrictions. As the development progresses, you would most probably require an RDBMS to develop and test your application before deploying it to use a production database server. I have written a series of posts on integrating Spring Boot for Oracle, MySQL, and PostgreSQL.

If you are wondering about the complexities of switching between databases, it’s actually quite simple. When you’re using Spring Data JPA with an ORM technology like Hibernate, the persistence layer is fairly well decoupled, which allows you to easily run your code against multiple databases. The level of decoupling even allows you to easily switch between an RDBMS and a NoSQL database, such as MongoDB. My previous post on Integrating Spring Boot for MongoDB covers that.

In this post, I will discuss Spring Boot integration for MariaDB. MariaDB started off as an offshoot of MySQL due to concerns of Oracle’s acquisition of MySQL. Led by the original developers of MySQL,