JPA tutorial – Inheritance strategy

JPA supports 3 inheritance strategies


For demonstration I will try to solve the problem of document management system where I need to store different types of documents, letter and invoice document. Here is the class diagram.


Document Class Diagram

Document Class Diagram

Single table strategy

For single table strategy JPA will create one table that has columns from all entities from the inheritance tree.

Create table SQL:

Observe the DOCUMENT_TYPE column, this is the discriminator column used by JPA to distinguish document types.


Code for all classes involved

Abstract Document Entity


@MappedSuperClass marks non entity super class.

Document Entity


In the DocumentEntity I have specified that

  • This is an entity
  • Inheritance is SINGLE_TABLE
  • Entity should be  mapped to table named DOCUMENT
  • Discriminator column is named DOCUMENT_TYPE
Invoice Document Entity

Invoice Document entity extends the Document Entity and important part is the annotation DiscriminatorValue. I will get to get in a bit.

Letter Document Entity

Letter Entity is similar to the Invoice Entity

Spring Repository and Unit Test

I will use spring repository to have CRUD support and write a unit test that will demonstrate insert and select all functionalities.

After this test is executed next SQL queries are used.

Creating entities SQL

Observe the INV and LET values, this are the values from the discriminator value specified above.

Select SQL

This is the simple select all query.

Joined strategy

To demonstrate joined strategy few changes must be done in the entities annotations. Unchanged parts are not shown in the listings.

Here is the list of changes

  • @Inheritance strategy is changed to InheritanceType.JOINED
  • @DiscriminatorColumn is removed since it does not have any effect in hibernate
  • @DiscriminatorValue is removed from Invoice and Letter
  • @Table is added

In the MySQL has 3 tables now, here is the diagram

MySQL table diagram

MySQL table diagram

Creating entities SQL

Select SQL

Select is not totally different with two left outer joins


I hope that this tutorial will help you to decide what inheritance strategy should you choose.

Spring JPA Repositories tutorial


Using Spring Data JPA repositories can give you head start in the project and save you from boilerplate code. In this post I will show you how to:

  • Wire important beans DataSource, JpaVendorAdapter, EntityManager and TransactionManager
  • Enable JPA repositories using @EnableJpaRepositories
  • Specify Pomodoro entity
  • Create JPA Repository
  • Specify query using method name, @Query annotation with named parameters, using native sql query
  • Specify update query

Wiring data related beans

There are number of data related beans that you need to wire in order to allow your application to access database with transactions enabled. First you need to create data source. Good approach is to have spring Profiles enabled so that you use one datasource for production and other for development like environments. This post can help you with spring profiles.


Specifying datasources is done using next lines of code

Here we have two datasource beans created depending of the profile enabled DEV or PRODUCTION. One datasource is BasicDataSource that connects to your database server depending of the environment properties that are set.

For this example I have included using  @PropertySource. Check more about property place holders here.

JPA vendor adapter

Vendor adapter bean needs to be created here we are using HibernateJpaVendorAdapter with H2 database, show sql , generate Ddl and database plaform h2Dialect.

Note: You might not want to set generateDDl to true since this will add all missing columns and tables in the database.

Entity manager factory

Entity manager factory needs datasource , vendor adapter and packages to scan. Scanned package should have classes annotated with @Entity so that entity manager can pick them up.

Transaction manager

At last we need transactions in our application, for this we will specify transaction manager bean using:

Transaction management needs to be enabled using annotation  @EnableTransactionManagement. There are few parameters you should consider using

  • mode , default is AdviceMode.PROXY. Other option is ASPECTJ.
  • order, default is Ordered.LOWEST_PRECEDENCE
  • proxyTargetClass, default is false

Finally we need to enable JPA repositories using especial annotation

Specified package contains the repositories.

JPA Repositories

Lets create one simple repository that will have CRUD methods

Ok is is really this simple?

Yes , extending CrudRepository interface will create JPA repository that has CRUD methods . If you check the code of CrudRepository

you will notice that it has one annotation @NoRepositoryBean. This annotation tells spring that this class is intermediate repository that is not supposed to be wired.

Beside CrudRepository you have Repository interface, this interface is empty and holds no mehtods. It is up to you if you want to copy method from CrudRepository to allow  for example deleting the entities .

Sorting and paging is done using especial interface

Sort is created using the list of orders that are property with direction ( ascending and discending). Here is a simple example that will sort pomodoros by name.

Pageable allows you to get results in pages and sorted ( sorted is optional ). Here is the Pageable example

PageRequest has few constructors you can use like that can sort results too.

You can decide what spring interface to extend and add your custom methods Repository, CrudRepository or PagingAndSortingRepository. All of them are parameterized using Entity and class of the primary key.

Creating custom queries

Query can be specified in multiple ways, one is of course manually additionally query can be written natively and using method naming.

Lets observe the entity class Pomodoro so that you can understand the custom query part.

Pomodoro entity is simple, it has id and name.

Using method name strategy should be your fist choice since is is easy to use, here is how it goes. One nice example is find pomodoro by name.

List<Pomodoro> findByNameLike(String name);

Method name consists of

  • findBy
  • property name (Name)
  • modifier ( Like)

Lets assume that Pomodoro has some other properties like Description method would be named findByNameLikeAndDescriptionLike.

Spring is packed with modifiers, here is the table picked up from spring reference.

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Between findByStartDateBetween … where x.startDate between 1? and ?2
LessThan findByAgeLessThan … where x.age < ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<Age> ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection<Age> age) … where x.age not in ?1
True findByActiveTrue() … where = true
False findByActiveFalse() … where = false

If you have complicated query method can be very long and hard to use, then maybe you can use @Query annotation where you can write your query using JPQL.

Annotated method parameters are then mapped to query, here we can map using order of the parameter and using @Param annotation. Here is the example of both

Modifying Query

You can create query that modifies the data, to do this you need to  use annotation @Modifying to tell spring what you want to do. Example


Here are few nice examples that will help you write your own queries.

Injecting JPA Repository

To use your custom jpa repository all you need to do is inject it like this


In second part i will go through advanced JPA repository features.

Spring Mysql and H2 DataSource with Profiles


In this tutorial I will demonstrate how to use

  • BasicDataSource for MySQL
  • H2 Embedded Java SQL DataSource
  • Spring profiles

MySQL DataSource

In order to create BasicDataSource first you need to add required libs, here is the gradle example

when we have this in place we need to create DataSource Bean, here is  example that demonstrates few things

  1. Wired environment values that are used to configure BasicDataSource
  2. @Profile condition is used

In order to use environment properties we need to add spring property placeholder first this is done using @PropertySource annotation.

H2 embedded database

Using Embedded database is super easy, here is how to configure it using EmbeddedDatabaseBuilder

Here is how to add required library for H2

Spring profiles

I have written before about spring profiles and how to use them here. For this application I will setup only default profile that can be overridden using jvm parameter"PRODUCTION"

Default profile is set in class that extends  AbstractAnnotationConfigDispatcherServletInitializer


This is really nice way to setup your data configuration, it is important to say that developers do not need to do anything in order to run app using in memory database but additional effort is required for production.

If you choose to configure default profile you can do so using java opts like this:

Happy coding.

Spring MVC Framework Tutorial


In this tutorial I am going to cover spring MVC by creating nice examples on how to

  • Bootstrap your application
  • Add REST APIs
  • Add Services with method security
  • Handle exceptions
  • Add security layer that will force users to authenticate
  • Unit test for Service and Rest Controller


Bootstrapping spring application is done using several classes that spring gives by default

  • AbstractAnnotationConfigDispatcherServletInitializer

  • WebMvcConfigurerAdapter

First we must create WebInitializer class that will extends  AbstractAnnotationConfigDispatcherServletInitializer class, here we will tell spring what is our root config and our servlet config class( or classes) along with servlet mapping path. Child class will be automatically scanned by spring so that we do not have to do anything.

Here is the example:

Observe that we have set servlet mapping to path / and that we have two spring config classes PomodoroServletConfig  and PomodoroRootConfig .

  • PomodoroServletConfig is used to configure RestControllers and static content handlers.
  • PomodoroRootConfig is used to wire spring beans and other configurations like data sources, security and other



Lets go through all annotations in above class:

  • @Configuration marks this class as spring configuration class
  • @ComponentScan helps spring find other beans for this case services and security configuration classes ( we will go through this latter).
  • @Import tells that spring should import specified configuration class
  • @PropertySource tells spring that it should import property file into the environment in this case that can be found in the class path



Most important annotation is @EnableWebMvc  annotations that enables Spring MVC, also it is equivalent to  <mvc:annotation-driven /> for XML configurations.

Observe that we have used ComponentScan annotation so that all of our RestControllers are auto configured.

I have added resource handler that will help us download static content like photos for example  will download file from   classpath:/META-INF/public-web-resources/logo.png

Note: ComponentScan can accept class as well, using class is better approach since it does  not fail after renaming package. Here package is used so that example can be easily comprehended.

Even now with nothing more but 3 classes we can start our application :), problem is that it would not be able to do anything since we did not add any REST APIs yet.

Spring REST APIs

First thing is first , lets add one Rest Controller to this application. Using @RestController  and @RequestMapping  we are telling spring to map method getPomodoros  to path /.

Response is in JSON format since we have added jackson libs to this project, spring automatically enables JSON response by default. You can examine this feature in class


Ok, so now we have our application set and running. Lets go through other options and features.

RequestMapping additional options

RequestMapping annotation can be added on method and on the class, this can be quite handy in case where we have main path and extra paths for actions like update, delete and so on… For example our main path would be /pomodoro  and extra path is /pomodoro/find-max, as you can see we have /pomodoro twice :(. Here is how to solve this:

URL to getMax() will be /pomodoro/find-max

HTTP Request Type currently is not specified, this means that all http request types ( GET, POST, PUT… ) that use this URL will hit method getMax.

RequestMapping options:

  • Value, used to filter path for example /find-max
  • Method, used to filter http request method. Possible values are enum values RequestMethod {GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE}
  • Params, used to filter requests that have required parameters, example is myParam=myValue, or myParam!=myValue , or !MyParam
  • Headers, used to filter requests that have required headers present, example is My-Header=myValue, My-Header!=myValue or !MyHeader, also My-Header=my* can be used.
  • Consumes, used to filter consumable media types of the request, example is consumes={“text/plain”, application/*} or !text/plain
  • Produces, used to filter producible media types example is produces = “text/plain” or produces = {“text/plain”, “application/*”}

Above RequestMapping options are used to filter request but when request hits the method we can map request parameters to method arguments using few handy annotations.

Here are all possibilities for parameter annotations

  • @PathVariable, lets assume that our url is /find-max/{pomodoroType} when request comes as /find-max/AwesomePomodoro  we would like that AwesomePomodoro value maps to one method argument that we like. @PathVariable String pomodoroType .
    We can also map path variable to custom named parameter by specifying PathVariable value @PathVariable("customParam"). This also works for enumerations.
  • @CookieValue
  • @RequestHeader
  • @RequestParam
  • @RequestBody, is used to tell spring to convert request body to the instance of object that we specify(ie PomodoroRequestJson).
  • @MatrixVariable, is used to max matrix parameters here is nice example from spring official page

Services and @Autowire annotation

To make things interesting lets add one service that will be autowired into rest controller. Service is going to be PomodoroService and its implementation PomodoroServiceImpl. Two thins are important in the service implementation class, first is that class is annotated with @Component making the class interesting for component scanning and @Secured annotation on methods that helps us make sure that only users with correct role can “call” this method.

To wire PomodoroService into RestController we can use @Autowire annotation.

Handling exceptions

When exception occurs it is important that your backend responds in a such way that caller will be able to understand the problem, process it and respond to it in proper manner ( show error message to the user). Here is one RestController that throws exception called MissingPomodoroException.

Observe usage of @PathVariable , idea is that this method returns pomodoro with specified id. In case when it is missing HTTP response should be  HttpStatus.NOT_FOUND.  We could handle exceptions here in the getPomodoro method but this would not be good approach. It is better to have one class( or small set of classes) that deal with exceptions and convert them to responses with right details.

To do this we will define a class with annotation @ControllerAdvice that extends ResponseEntityExceptionHandler.

ResponseEntityExceptionHandler is the class that handles default spring exceptions like NoSuchRequestHandlingMethodException and other. Just override methods that you are interested in the specify your own response.

Here is how to handle exceptions specific to your application

I have defined class ErrorResponse that will be standard response when error occurs . Here how this response looks like with correct HttpStatus NOT_FOUND.

Security layer

Hm, looking what we covered so far you may noticed that everyone can get read anything :), this is never smart idea. Lets fix this in a nice way using spring security. Here is a short list of what we need to do to accomplish this.

  • Enable Spring MVC Security
  • First we are going to secure all paths so that only registered users can add and list pomodoros
  • Demonstrate several ways of authentication

Enable Spring security with method security

For spring security to be enabled two components are required

  1. Security Web initialiser
  2. Web security configurer

Here we have securityConfig where we have enabled in memory authentication for two users (admin and user) and paths security is set like this:

  • /pomodoro/** can be accessed by users only
  • /signup can be accessed by all
  • All other paths can be accessed by authenticated users
  • csrf is disabled
  • Basic authentication is enabled
  • All unauthenticated users have role Anonymous.

Setting up spring MVC with spring security is not hard and with just few classes and lines of code you have have nice REST API enabled backend application with security.

You may have noticed @EnableGlobalMethodSecurity this handy annotation enables us to secure our service methods. Check the PomodoroServiceImpl methods you will notice @Secured annotation.

Unit Testing

Testing the services and rest controllers is every developer primary concern , in next short code listing I will show how to test PomodoroService and PomodoroCollectionResource.

Testing PomodoroService


Testing RestControllers

RestControllers testing can be a bit complicated because of number of things developer needs take care of , one is http response, http request , authentication …  Here is a simple example that demonstrates how to test json response with single object or array or objects in this case pomodoros.


I do really hope that this post will help you kick start your spring MVC projects. In future posts we will go through other spring projects.

Happy coding.


Spring AOP tutorial

In this tutorial I will go through all important spring AOP details that will enable you to use AOP with ease.

  • How to enable AOP in java
  • How to create Aspect
  • How to create Point cut with designators
    • args()
    • @args()
    • execution()
    • target()
    • @target()
    • within()
    • @within
    • @annotation
  • How to use advices ( Before, After, AfterThrowing ,After returning) with especial attention on how to pass parameters to your aspect methods
  • How to use Around advice

Classes, interfaces and annotations Used in this tutorial

I will use only few classes in this tutorial, first is the Knight interface and its implementation MajesticKnight, observe two annotations @Primary and @MethodAnnotation. Next we have KnightWeapon that is annotated with @ArgAnnotation. This annotations will come to be important when in next code examples.

How to enable spring AOP

Enabling spring AOP in java is done using  @EnableAspectJAutoProxy, lets observe configuration class KingConfig that creates two beans, one is MajesticKnight and other is KnightOneMethodAspect.

If you are using component scan in your configuration you can use @ComponentScan and not create beans manually.

How to create spring aspect

Here is one example of aspect , notice the annotation @Aspect (org.aspectj.lang.annotation.Aspect) this will marks this class as aspect. We also have one empty method getKnightName that is annotated with @Pointcut, every aspect must have pointcut definition to explain what join points should be woven. In this case method getKnightName of bean Knight is woven.

At last we have method that is executed before getKnightName is called, it is annotated with  @Before("getKnightName()") advice @Before tells when method is to be executed and value of annotations tell what point cut is relates to.


Spring offers few advices that we can use

  • Before
  • After
  • AfterThrowing
  • AfterReturning
  • Around

Lets expand the KnightOneMethod aspect a bit to show how to use all of this advices.

Order in which annotated methods are executed in this aspect is:

  1. @Before
  2. @After
  3. @AfterReturning or @AfterThrowing , this depends if your method returns anything or throws exception

Lets observe two interesting advices AfterReturning and AfterThrowing, here it is important to notice that methods receive the returned value and thrown exception.

@Around advice

Above advices can be replaced with one advice named @Around, here is changed code that demonstrates this advice.

It is important to notice that joinPoint of class ProceedingJoinPoint has a method proceed() that must be called in order to spring to actually call method in this case getKnightName.

ProceedingJoinPoint class is very interesting here are few methods that you may find interesting

  • Object getTarget();  Returns the target object.

  • Object[] getArgs();  Returns the arguments at this join point

  • Signature getSignature();  Returns the signature at the join point

  • String getKind();  Returns a String representing the kind of join point

Designator args()

Designators are used to filter all join points that match some specific criteria. Args and used to filter all join points that have certain  parameter types. If you check the Knight interface and its methods it has two methods with String type parameter.

StringBefore method does not accept any parameters, lets see how to change that.

It is important to notice that test is the parameter name, in this example it is named test. In case your desired join point has multiple parameters adding .. will take this into account.

Designator @args

Designator @args works in a similar way as args with just one difference, it selects join points that have parameters that are annotated with desired annotation.

This is the Knight method we want to select  void setKnightWeapon(KnightWeapon knightWeapon); , KnightWeapon class is annotated with @ArgAnnotation(value = 99) .

Lets try to spice this up a bit and mix it with args designator.

We have method pointcut that selects all methods in Knight bean that have KnightWeapon as argument, before we have learned how to pass pass argument in our advice. Now observe string pointcut we have combined designators and added  @args(rs.pscode.model.ArgAnnotation)

Problem is clearly visible, we sometimes want to have annotation as parameter to the advice method. Here is an example that will show you how to do this.

Do you see the similarity between args and @args when you want to pass a method argument? Here is once more so that is clearly visible, this is very important as it works the same way on other designators we are going to cover in this tutorial.


Designator @annotation

When you want to select join points that are annotated with annotation of your choice you can use @annotation. MajesticKnight has one method that is annotated with MethodAnnotation, lets create one aspect that will add Before advice.

Designator target

To target join points of given type target designator is used. In this case we are targeting all methods from Knight bean.

Designator @Target

MajesticKnight class is annotated with @Primary annotation, if we want to select all methods from beans that are annotated with this annotation @target is to be used. Here is nice example for this


Designator within

In above example we selected join points that are located in class that is annotated or is of certain type, what if we want to select all join points in desired package ? This is where @within and within come handy



Spring AOP is offers really nice solution to your cross cutting concerns , it allows you to decouple your classes and put one concern in one place. Examples of AOP is @Transactional that I am sure you know.

Let the spring be with you 🙂


Spring util:map


It is a common case to wire java.util.Map and then to inject the map into your bean. In this short tutorial i will show you how to do that.


Here is how to configure your Map in XML.

Observe attribute map-class, here I have specified what Map implementation used is going to be used.

Ordered Map

In upper xml example I have used HashMap, it is important to notice that HashMap does not have ordered keys. This can be important im many cases , so here is how to set this up using LinkedHashMap.


Here is part from java doc Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)



Here is how to inject valueMap in your bean.


Spring is awesome 🙂

Spring property placeholder


It is very common not to hardcode some of the configuration properties like database password , username and other. But instead to put is in a placeholder and then wire it. lets import properties and use them in the application.

Java configuration

I have created a simple property file named with next content

name=My Knight

Plan is to use value name as a property of Knight bean.

Here i have used @PropertySource annotation to specify property file I want to include. Here is how to include multiple property sources.

Problem with upper example is that it wires Environment just to use one property, this does not make much sense. Solution is @Value annotation.

@Value annotation

Value annotation will use the value of environment property and set the property of the class. In this case “My Knight”

XML Configuration

Same can be achieved with XML configuration using context:property-placeholder.


Spring is awesome!

Spring ambiguity problem


Spring ambiguity problem is a common misconfiguration problem it occurs when you have more then one bean that qualifies for wiring, in this case spring can not solve the problem and throws exception


In this tutorial I will show you what couses this problem and how to address it.

To demonstrate the problem I will use one interface Knight and two implementations DevelopmentKnight and ProductionKnight. Here is the code

Java Configuration [NoUniqueBeanDefinitionException]

To wire the beans I will use java configuration.

Here I have used name property to name the beans accordingly , in case name property is not used names of the beans would be:

  • getKnight
  • getKnightProd

spring will name the beans using the method name that creates it. Since this would not be fun :), I have added especial names.

Note: This configuration will throw exception NoUniqueBeanDefinitionException, reason is clearly visible in the MainConfig class above I have created two methods annotated with @Bean that returns same interface. This will confuse spring as it will not be able to decide what method should be used to create Knight bean.


Unit Test

To see how problem occurs I will use this test class

If you run this test class exception will be thrown and test will fail.

@Qualifier annotation

To solve the problem of ambiguity lets first use @Qualifier annotation to instruct spring what implementation we really want. Here is the modified test class

If you run this example all will be green !

@Primary annotation

Another way of dealing with ambiguity is to instruct spring how to solve the problem when it occurs by marking one bean as primary, this is where @Primary annotation comes in. Observe modified configuration.

As you can see I have added @Primary annotation and now spring knows how to solve the ambiguity problem.

@Primary annotation can be mixed with @Qualifier, lets say that in some especial case we want to autowire ProductionKnight, here is how to do this


Spring is awesome!



In this tutorial I will show you how to use SpEL using real life examples in the world of Knights and Swords 🙂

Here are interfaces and implementations that are going to be used in this tutorial


Set Literal value XML

Lets see how to set literal value using p namespace

Set Literal value @Value

For this we need to use annotation @Value.

NOTE: It is important to add  <context:annotation-config /> in your XML so that @Value annotation works.

Set other bean value XML

In this example I will show you how to set property of your bean using value from property of other bean.

Set other bean value @Value

Wire beans together using SpEL

Lets initialize knight bean using SpEL and set his weapon this way

Use Static Methods

You can use static methods like this, just use special T operator can be used to specify an instance of java.lang.Class and invoke your static method.


I hope that this examples will come handy.


Spring Profiles Tutorial


From Spring version 3.1 profiles are supported. This is a really nice feature that enables you to have environment specific beans wiring setuped in super easy way. In this tutorial I will show you how to leverage profiles spring feature. We will use  POJO Knight and two  implementations.

Spring XML Profiles setup

You saw that we have two implementations of Knight one to be used in production and other to be used in development environment. Lets see how to do that.

Observe tag <beans> and profile attribute, for dev profile spring will

  • create bean knight
  • use implementation DevelopmentKnight
  • set property knightName to be “Dev Knight”, here I have used p namespace to set the property.

For prod profile I want to use different implementation with different property value.

Note: Profile attribute can be set on root beans tag and on child beans tags as well.


Spring XML profiles demonstration

Here I am using ClassPathXmlApplicationContext to load the xml config, after this I set the active profile(s) and refresh the context. If you run this example you will see:

Dev Knight


Spring java profiles setup

Lets see how to wire our knights beans using java configuration. For this we need JavaConfig class with @Configuration annotation.

Spring java profiles demonstration

Here I will load prod profile and print class name of the injected bean.

As you see it is super easy to load annotation config application context and register correct configuration class.

Activate Spring profile

There are multiple ways to activate spring profile.






Unit Testing Spring profiles

Lets see how to test our profile setup. Here is the simple example that makes sure that all works .

To test xml configuration we will change the test in minor way like this


Spring is awesome, right ?