Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>>EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with SpringCloud:

>> Join Pro and download theeBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockitolibrary makes it easy to writeclean and intuitive unittests for your Java code.

Get started with mocking and improve your application testsusing ourMockito guide:

Download theeBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the SpringWebFlux module, which has been improved upon ever since. Getstarted with the Reactor project basics andreactive programmingin Spring Boot:

>> Join Pro anddownload the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download theE-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download theE-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download theE-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore theeBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through theLearnSpring course:

>> LEARNSPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building afullREST API with the framework:

>>The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advancedfunctionality within the Core to the deep OAuth support in theframework.

I built the security material astwo full courses - Core andOAuth, to get practical with these more complex scenarios. Weexplore when and how to use each feature andcode through it onthe backing project.

You can explore the course here:

>> Learn SpringSecurity

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle thecomplexity ofJPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided referencecourse:

>> CHECK OUT THECOURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — withOpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy toput off. That’s where OpenRewrite comes in. The open-sourceframework for large-scale, automated code transformations helpsteams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite atModerne run live, hands-on training sessions — one for newcomersand one for experienced users. You’ll see how recipes work, how toapply them across projects, and how to modernize code withconfidence.

Join the next session,bring your questions, and learn how to automate the kind of workthat usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the releaseprocess, to ensure that new code doesn't break the existingfunctionality. As the codebase evolves, we want to run these testsfrequently to help catch any issues early on.

The best way to ensure these tests run frequently on anautomated basis is, of course,to include them in the CI/CDpipeline. This way, the regression tests will executeautomatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests usingSelenium, and then include them in our pipelineusing GitHubActions:, to berun on the LambdaTest cloud grid:

>> How to Run SeleniumRegression Tests With GitHub Actions

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>> EXPLOREACCESS NOW

1. Overview

This article will focus onsimplifying the DAO layer by using a single, generified Data Access Object for all entities in the system, which will result in elegant data access, with no unnecessary clutter or verbosity.

We’ll build on the Abstract DAO class we saw inour previous article on Spring and Hibernate, and add generics support.

Further reading:

Introduction to Spring Data JPA

Introduction to Spring Data JPA with Spring 4 - the Spring config, the DAO, manual and generated queries and transaction management.

A Guide to JPA with Spring

Setup JPA with Spring - how to set up the EntityManager factory and use the raw JPA APIs.

Auditing with JPA, Hibernate, and Spring Data JPA

This article demonstrates three approaches to introducing auditing into an application: JPA, Hibernate Envers, and Spring Data JPA.

2. The Hibernate and JPA DAOs

Most production codebases have some kind of DAO layer. Usually, the implementation ranges from multiple classes with no abstract base class to some kind of generified class. However, one thing is consistent – there isalways more than one. Most likely, there is a one to one relation between the DAOs and the entities in the system.

Also, depending on the level of generics involved, the actual implementations can vary from heavily duplicated code to almost empty, with the bulk of the logic grouped in a base abstract class.

These multiple implementations can usually be replaced by a single parametrized DAO. We can implement this such that no functionality is lost by taking full advantage of the type safety provided by Java Generics.

We’ll show two implementations of this concept next, one for a Hibernate centric persistence layer and the other focusing on JPA. These implementations are by no means complete, but we can easily add more additional data access methods are included.

2.1. The Abstract Hibernate DAO

Let’s take a quick look at theAbstractHibernateDao class:

public abstract class AbstractHibernateDao<T extends Serializable> {    private Class<T> clazz;    @Autowired    protected SessionFactory sessionFactory;    public void setClazz(final Class<T> clazzToSet) {        clazz = Preconditions.checkNotNull(clazzToSet);    }    public T findOne(final long id) {        return (T) getCurrentSession().get(clazz, id);    }    public List<T> findAll() {        return getCurrentSession().createQuery("from " + clazz.getName()).list();    }    public T create(final T entity) {        Preconditions.checkNotNull(entity);        getCurrentSession().saveOrUpdate(entity);        return entity;    }    public T update(final T entity) {        Preconditions.checkNotNull(entity);        return (T) getCurrentSession().merge(entity);    }    public void delete(final T entity) {        Preconditions.checkNotNull(entity);        getCurrentSession().delete(entity);    }    public void deleteById(final long entityId) {        final T entity = findOne(entityId);        Preconditions.checkState(entity != null);        delete(entity);    }    protected Session getCurrentSession() {        return sessionFactory.getCurrentSession();    }}

This is an abstract class with several data access methods, that uses theSessionFactory for manipulating entities.

We are using Google Guava’s Preconditions here to make sure that a method or a constructor is invoked with a valid parameter value. If Preconditions fails, a tailored exception is thrown.

2.2. The Generic Hibernate DAO

Now that we have the abstract DAO class, we can extend it just once.The generic DAO implementation will become the only implementation we need:

@Repository@Scope(BeanDefinition.SCOPE_PROTOTYPE)public class GenericHibernateDao<T extends Serializable>  extends AbstractHibernateDao<T> implements IGenericDao<T>{   //}

First,note that the generic implementation is itself parameterized, allowing the client to choose the correct parameter on a case by case basis. This will mean that the clients get all the benefits of type safety without needing to create multiple artifacts for each entity.

Secondly, noticethe prototype scope of this generic DAO implementation. Using this scope means that the Spring container will create a new instance of the DAO each time it’s requested (including on autowiring). That will allow a service to use multiple DAOs with different parameters for different entities, as needed.

The reason this scope is so important is due to the way Spring initializes beans in the container. Leaving the generic DAO without a scope would mean usingthe default singleton scope, which would lead to a single instance of the DAO living in the container. That would obviously be majorly restrictive for any kind of more complex scenario.

TheIGenericDao is simply an interface for all the DAO methods so that we can inject the implementation we need:

public interface IGenericDao<T extends Serializable> {    void setClazz(Class< T > clazzToSet);    T findOne(final long id);    List<T> findAll();    T create(final T entity);    T update(final T entity);    void delete(final T entity);    void deleteById(final long entityId);}

2.3. The Abstract JPA DAO

TheAbstractJpaDao is very similar to theAbstractHibernateDao:

public abstract class AbstractJpaDAO<T extends Serializable> {    private Class<T> clazz;    @PersistenceContext(unitName = "entityManagerFactory")    private EntityManager entityManager;    public final void setClazz(final Class<T> clazzToSet) {        this.clazz = clazzToSet;    }    public T findOne(final long id) {        return entityManager.find(clazz, id);    }    @SuppressWarnings("unchecked")    public List<T> findAll() {        return entityManager.createQuery("from " + clazz.getName()).getResultList();    }    public T create(final T entity) {        entityManager.persist(entity);        return entity;    }    public T update(final T entity) {        return entityManager.merge(entity);    }    public void delete(final T entity) {        entityManager.remove(entity);    }    public void deleteById(final long entityId) {        final T entity = findOne(entityId);        delete(entity);    }}

Similar to the Hibernate DAO implementation, we’re using the Java Persistence API directly, without relying on the now deprecated SpringJpaTemplate.

2.4. The Generic JPA DAO

Similar to the Hibernate implementation, the JPA Data Access Object is straightforward as well:

@Repository@Scope( BeanDefinition.SCOPE_PROTOTYPE )public class GenericJpaDao< T extends Serializable > extends AbstractJpaDao< T > implements IGenericDao< T >{   //}

3. Injecting This DAO

We now have a single DAO interface we can inject. We also need to specify theClass:

@Serviceclass FooService implements IFooService{   IGenericDao<Foo> dao;   @Autowired   public void setDao(IGenericDao<Foo> daoToSet) {      dao = daoToSet;      dao.setClazz(Foo.class);   }   // ...}

Springautowires the new DAO instance using setter injection so that the implementation can be customized with theClass object. After this point, the DAO is fully parametrized and ready to be used by the service.

There are of course other ways that the class can be specified for the DAO – via reflection, or even in XML. My preference is towards this simpler solution because of the improved readability and transparency compared to using reflection.

4. Conclusion

This article discussed thesimplification of the Data Access Layer by providing a single, reusable implementation of a generic DAO. We showed the implementation in both a Hibernate and a JPA based environment. The result is a streamlined persistence layer, with no unnecessary clutter.

For a step by step introduction about setting up the Spring context using Java based configuration and the basic Maven pom for the project, seethis article.

The code backing this article is available on GitHub. Once you'relogged in as aBaeldung Pro Member, start learning and coding on the project.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>>EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-Day FreeTrial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow deliveryleads to missed opportunities, innovation is stalled due toarchitectural complexities, and engineering resources areexceedingly expensive.

Orkes is the leading workflow orchestration platformbuilt to enable teams to transform the way they develop, connect,and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers canfocus on building mission critical applications without worryingabout infrastructure maintenance to meet goals and, simply put,taking new products live faster and reducing total cost ofownership.

Try a14-DayFree Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

TheApache HTTP Client is a very robust library, suitablefor both simple and advanced use cases whentesting HTTPendpoints. Check out our guide covering basic request andresponse handling, as well as security, cookies, timeouts, andmore:

>> Downloadthe eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky processwith manypotential pitfalls. A solid grasp of thefundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications withourJava Concurrency guide:

>>Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become astaple of Java development. The basic operations like iterating,filtering, mapping sequences of elements are deceptively simple touse.

But these can also be overused and fall into some commonpitfalls.

Toget a better understanding on how Streams work and howto combine them with other language features, check out our guideto Java Streams:

>> Join Proand download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring,through theLearn Spring course:

>> CHECK OUTTHE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebasesdon’t always keep up. Frameworks change, dependencies drift, andtech debt builds until it starts to drag on delivery. OpenRewritewas built to fix that: an open-source refactoring engine thatautomates repetitive code changes while keeping developer intentintact.

The monthly training series, led by the creators and maintainersof OpenRewrite at Moderne, walks through real-world migrations andmodernization patterns. Whether you’re new to recipes or ready towrite your own, you’ll learn practical ways to refactor safely andat scale.

If you’ve ever wished refactoring felt as natural — and as fast— as writing code,this is a goodplace to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Proare33% off untilnextMonday:

>> EXPLOREACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
Do JSON right with Jackson - book cover
Do JSON right with Jackson - icon
Do JSON right with Jackson
Download the E-book