Spring, Hibernate, EhCache Recipe

A Simple Scenario explaining the Usage and Performance, when using EhCache (2nd Level Cache of along with Hibernate in a Spring environment. The performance results are taken using mySQL as the Database. 

Though this Example is from Spring 2.5.x and Hibernate 3.x and EhCache 1.4, MySQL 5.0 => The Concepts Demonstrated will Continue to Hold Good for any Version of any Make of Second Level Cache Product with Hibernate (Optionally, Spring) such as Infinispan, Redis, Hazelcast, ...

[Download Sample Code] Please be informed that the size is about 10MB; as i have provided all the dependencies.

In this example, I need to retrieve close to 5,000 records in a single fetch and then cache this information. As usual, setup Spring contexts in your Spring configuration file. I have just one class, which is a Hibernate DAO, HibernateDoctorDAO.java. The dependency injection hierarchy is dataSource sessionFactory hibernateTemplate. hibernateTemplate is then injected into the HibernateDoctorDAO.java at runtime by the Spring Framework.

The Implementations of Each of These Are:
dataSource > org.apache.commons.dbcp.BasicDataSource
sessionFactory > org.springframework.orm.hibernate3.LocalSessionFactoryBean
hibernateTemplate > org.springframework.orm.hibernate3.HibernateTemplate

The results clearly shows the difference in performance with EhCache enabled, even in this simple example:
 
PERFORMANCE COMPARISON (In Seconds)
==============================
QUERY FETCH TIME (INITIAL): 0.599
QUERY FETCH TIME (HIBERNATE CACHE): 0.212
QUERY FETCH TIME (2ND LEVEL CACHE): 0.091
Version Reference > Spring-2.5, Hibernate-3.0, EhCache-1.4, mySQL-5.0
 

Instructions: Unzip the file and start by creating the database. Any mySQL database that is compatible with the MySQL Connector 5.0.8 is fine for this example. You will have to create the database data_explosion (USERNAME: root, PASSWORD: architect.2012) and the table DOCTOR_TABLE. You can use the provided doctor.sql as reference. Then run the java standalone com.sumsoft.spring.orm.hibernate.dataload.JDBCDataLoader to create and load a large number of arbitary records into the DOCTOR_TABLE. You can ignore or remove every invocation that is to PATIENT_TABLE, as this is only additional for this example. Then use spring_hibernate_cache.bat to run the application. Though not tested on UNIX, you may write a script similar to the batch file to run this application. 

JPA Goes Even Easier With its Buddy

So, Hello World... After almost a year of development, the first version of JPA Buddy has finally been released! This is a free tool that is supposed to become your faithful coding assistant for projects with JPA and everything related: Hibernate, Spring Data, Liquibase, and other mainstream stacks.

"Why would I use it?" - this is a fair question towards any new tool or framework. In short, if you use JPA for data persistence, JPA Buddy will help you to be more efficient. In this article, I'll present an overview of the tool. I hope it will take its fair place among the most loved tools for Java developers, ones who use JPA, Spring, Liquibase, and of course the most advanced Java IDE - IntelliJ IDEA.

Java and Hibernate: Entity Management in Multi-Client, Single Codebase Apps

When developing an application for only one client or only a single version, the main subjects you focus on are how to implement the features, security, performance, design, time to market, etc. What will happen if the number of clients increases, and each one of them has different requests that contradict each other? Are we going to duplicate our codebase and have different apps, which we have to implement common features to every instance separately? Or are we going to manage them from one codebase?

Diversity in labels might be managed with different property files, but will this be enough for all kinds of requests? The flow in the logic might be directed with control blocks. What will happen to them when you have 100 different clients? What will happen to the readability/manageability of the code? We might decide to extract the logic that differs from one client to another and have multiple microservices. This will allow us to have clean code, but will we be able to turn all the logic that differs from client to client into microservices? Is our structure suitable for this process? How about managing and deploying all those services? Is it worth the cost?

How to get Type-Safe and Intuitive Hibernate/JPA Queries

A large proportion of Java database applications are using Hibernate/JPA to bridge the gap between Java and SQL. Until recently, we were forced to mix Java and JPQL or to use complex imperative criteria builders to create database queries. Both of these methods are inherently neither type-safe nor very intuitive.  The newly launched  open-source library JPAstreamer addresses these issues by allowing you to express Hibernate/JPA queries using Java Streams. This means we can avoid any impedance mismatches between JPQL/HQL and Java and get full type-safety. In this article, I will show you how to put Java Stream queries to work in your application using JPAstreamer.

JPAstreamer in a Nutshell

As mentioned, JPAstreamer allows JPA queries to be expressed as standard Java Streams using short and concise, type-safe declarative constructs. This makes our code shorter, less complex, and easier to read and maintain. Best of all, we can stick to using only Java code without needing to mix it with SQL/JPQL or other language constructs/DSL.

In short, we can query a database like this:

How JPAstreamer Can Help You Write Type-Safe Hibernate Code Without Unnecessary Complexity

For the past 10 or so years, JPA has been one of the most popular ways of accessing a database within the Java ecosystem. Even if you haven't heard of JPA directly, there is a high likelihood that you've heard of or even used one of the most popular implementations of the JPA API - Hibernate.

The reason why JPA is so popular is no secret - most of the inconveniences are abstracted from the user, making the API very intuitive to use. Let's say that in some random database exists a table called person with the following structure:

Deploy Quarkus Faster in the Cloud with Platform.sh. Part 4: Hibernate Search With Elasticsearch

Quarkus is, in its own words, a Cloud Native, (Linux) Container First framework for writing Java applications. It has become popular because of the amazingly fast boot time, incredibly low RSS memory. In this series of articles about Quarkus, we'll teach you how to deploy Quarkus with Hibernate search with Elasticsearch.

Full-text searching provides the capability to identify natural-language documents that satisfy a query, and optionally to sort them by relevance to the query.  Hibernate Search automatically extracts data from Hibernate ORM entities to push it to local Apache Lucene indexes or remote Elasticsearch indexes.

Spring2quarkus — Spring Boot to Quarkus Migration

Time to boot up your Spring with Quarkus. 


Recently the "fattest" of my Spring Boot based microservices became too big. The entire project was hosted on the AWS EC2 environment and the instances used were t2.micro or t3.micro. The service started to get down very often even with minimum load on it. The obvious option was to choose a bigger instance for the service (t3.small) which I did initially.

Mapping Java Entities for Persistence With Hibernate (Part 4)

Learn more about mapping Java entities for persistence with Hibernate.

This post explores additional Java ORM mapping features in Hibernate/JPA, focusing on entity association mapping. Make sure to check the earlier posts: part 1, part 2, and part 3.

You may also like:  Hibernate Mapping Many-to-One Using Annotations

Also as a reminder, Hibernate is a powerful and feature-rich library – these posts serve as an overview of how to use some of its features to map Java domain model classes to relational tables. There are other topics that can be looked up in the official documentation.

Hibernate Example

In this tutorial, you will see how to persist the Java objects using the Hibernate Object/Relational Mapping (ORM) framework. Hibernate automates ORM and considerably reduces the number of lines of code needed to persist the object in the database. This example demonstrates how to automatically generate code from the object/relational mapping file, thus saving the developers time. This helps the developers focus on the business problem rather than doing repetitive coding work.

Hibernate uses an XML document or the properties file to define the object/relational mapping. The object/relational mapping file contains the mapping between the Java object and the corresponding database table. This example illustrates how to create the ORM using the XML document.

Hibernate Mapping One-to-Many Using Annotations

In this example, you will learn how to map one-to-many relationship using Hibernate Annotations. Consider the following relationship between Student and Phone entity.

According to the relationship, a student can have any number of phone numbers.

Writing Type-Safe SQL Queries With JPA

JPA is a great technology that maps the database relational model to the Java object-oriented model. It retrieves data and persist back the changes very easily, but it lacks the ability to perform advanced queries. In fact, all the advanced SQL capabilities are simply locked to the Java developer until she chooses to write a hard-to-maintain SQL as a hard-coded string.

FluentJPA project aims to fill this gap in two ways:

Deadlock in Databases

From databases perspective, a deadlock is a phenomenon that occurs when two transactions are blocking each other.

In the figure above, we have a classic deadlock situation. Transaction A (old man transaction) holds a lock to resource A (Dogs), but it doesn't release it until it will acquire a lock to resource B (Cats) that is currently locked by transaction B (young man transaction). In the same time, transaction B (young man transaction) holds a lock to resource B (Cats), but it doesn't release it until it will acquire a lock to resource A (Dogs) that is currently locked by transaction A (old man transaction).

Easy Access to Data With Spring REST Data

Spring Boot offers fantastic support for accessing data with JPA through the use of interfaces that extends to the repository. If we add to this the ease with which REST services are created, as explained in this entry, we can make an application that offers an API to access our preferred database very easily.

But if we want to implement HATEOAS in our project or if there are a lot of entry points in our API, we must write a lot of code. To solve this problem, Spring Boot offers the library Spring Data Rest. With it, we can write an API REST to access our database easily and without writing much code.

Caching in Hibernate With Redis

Hibernate is an open-source, object/relational mapping framework for the Java programming language. The goal of Hibernate is to help developers spare themselves from many tedious, manual data processing tasks. Hibernate is able to create mappings between Java classes and database tables, as well as data types in Java and SQL.

Any non-trivial application working with large quantities of data must rely on caching and other techniques to become more efficient. Caching is a strategy to improve the performance of an application by using a buffer to store frequently accessed data. By reducing the number of database requests and storing the data closer to the CPU, caching can significantly increase an application's speed.