Introduction to Spring and Hibernate (With Sample Code)

CWC
9 Min Read

Nowadays if you want to develop a complex Java application you need to use some frameworks which give you some basic tools to operate with them — to leverage your overhead of coding.

For example database connectivity can be quite a big time-consumer and very error prone because of the amount of possibilities and it is good to have a handy tool which is easily configurable and has a big community behind it to ask questions.

What is Spring and Hibernate, and why should I care?

You could ask your question “Why should I care about some frameworks if there is Java EE which has everything I need from one single vendor?” — and you are almost right. Java Enterprise Edition has the same capabilities Spring and Hibernate have: DI container, JPA (database access), AOP and so on…

However Java EE is based on ideas behind both Spring and Hibernate. Some functionality is not even in Java EE available which is already in Spring and Hibernate.

And the best part is: for Java EE you need an application server to run your application. For Spring and Hibernate you don’t.

Brief words about the Spring technology stack

The Spring Framework is stack based. The base is the Spring Core Container which includes the core features of Spring which are used by other modules to get implement the needed functionality.

Illustrated with an image from the Spring homepage

This means that you need the core package for all applications you want to use Spring — but you do not need the whole framework for a simple application (as with Java EE).

Spring Boot

Spring Boot is a Spring project which makes it more easy to create standalone applications with Spring. These applications are production ready too: you can deploy Spring Boot applications to Heroku (for example) and they are accessed by your customers.

The configuration of Spring Boot is managed from itself as far as possible. This means you have to add a very minimalistic configuration to your application and you are done, Spring takes care of everything else.

Brief introduction to Hibernate

Hibernate was created to leverage the connection between Java applications and relational databases because it is hard to map back and forth between a database table and a Java object.

And because Hibernate does this it reduces development time which is consumed by JDBC query-execution and data mapping.

Hibernate has a wide range of usage in the development world: mostly any Java application using databases uses an ORM tool — and there are only some applications which do not rely on Hibernate.

A simple example

What would be a long, introductory article without any example? This is why I have prepared a simple project with Maven and Spring and Hibernate to show in example what I was talking about.

The example will be very simple: I set up a Spring container and save some data into the database.
[sociallocker]

DOWNLOAD sample codes application with Spring & Hibernate

 
zip password: codewithc [/sociallocker]

Maven

I’ve created a Maven project to maintain the dependencies easier. This is because Spring and Hibernate are big projects and they have a lot of dependencies carrying Because of this if I or you want to create an application we would need to set up the classpath with an enormous amount of libraries.

Maven helps out and it downloads dependencies for the right version automatically.

As a best practice I encourage everyone to use properties as the dependency version numbering in the pom.xml files. This makes it easier to switch to a new version if available — and if you bind more dependencies from the same project you can update them easier at once.

Bill of Materials (BoM)

If not yet already encounter the problem of using third party software which requires the same dependencies as your applications in our case Spring. And naturally you will find distributions with other versions of Spring (older or newer) and then you have version mismatch. And version mismatch can result in various errors or side-effects compile time (happier case) or runtime (worst case). But the Maven BoM (Bill of Materials) gives a solution to this problem.

Annotation configuration

There are two approaches to configure your application: to use XML or annotations. In old times there existed the so called “XML-Hell” where you needed to configure everything through XML files. To leverage this annotation configuration was introduced — however this summoned the new term “Annotation-Hell”.

In this simple example I will use annotation-based configuration because in this case you can read plain old Java code to see what is configured — no need to open XML files when you encounter something.

To use Spring together with Hibernate you need in a minimalistic scenario only one class which has all required configuration annotations on or in it. However I’ve split it up into separate classes for the sake of brevity.

Basic configuration

It is not required but is a good practice to create a package containing the configuration classes. I’ve included these classes in the springhibernate.config package. As you can see there are two files:ApplicationConfiguration and PersistenceConfig. The first one is very plain: it only contains the required annotations:

@Configuration
@ComponentScan(basePackages = "springhibernate")

The @ComponentScan(basePacages = "springhibernate") tell Spring to use the springhibernate package to look for other configurations or beans to use later in the application.

The PersistenceConfigclass contains all the information needed to connect to the database and create sessions.

ApplicationService is the service which carries a transaction for the database calls to persisit the data.

Main is the main entry point of the application. It has the main method which kicks-on Spring adds a book to the database and prints all books from the database to the standard output.

You will notice that every time the application saves the same book into the database (at least the same name and ISBN) and gets a new ID to distinguish between all those values.

Executing the application

If you package the application with maven clean package you will find a JAR file called springhibernate-0.0.1-SNAPSHOT.jar in the target folder. To execute the application just call java -jar springhibernate-0.0.1-SNAPSHOT.jar and this was it. You should see some SQL statements created by Hibernate and the results printed to the console: the books contained in the database.

You can move this single JAR around and execute it where you want: it contains all its dependencies (Spring and Hibernate).

Conclusion

As you could see it is easy to create a powerful standalone application with Hibernate and Spring — and the configuration is easy too because you do not have to take care of as much typos as with using XML.

However this was just a very basic introduction to get you started. There are much more possibilities within Hibernate and Spring too which would need more examples and going more deeply into these frameworks.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version