ORM in Java is a bit of mess, take a look at the criteria interface API, its big. If you don’t want to use criteria you could write jpql instead, or you could use one of the various additional tools that are available such as QueryDSL , JOOQ and spring-data.

None of the above really hit the spot, the criteria api provides an interface for performing object oriented retrieval but its rather complex for the noob. Dynamic queries don’t cut it with jpql, and you still have to provide a dao/repository to run the query. QueryDSL and Jooq imho look a bit too heavy weight, I just want a friendly SOLID mechanism to access my entities, building upon the JPA interface.

Spring-data looks like a step up, you define a base interface for common functionality across all entities that extends the spring repository and then in each different repository you can add functionality specific to the entity :

public interface ProductRepository extends BaseRepository {
    List findByProductId(Integer id, Boolean deleted);
    List findByNameAndActive(String name , Boolean active);
    List findByNameAndActiveOrderByDateDesc(String name, Boolean active);

You then simply inject the interface into your service/controller layer – spring creates the implementation for you by parsing the method name. This has the added benefit that it is compatible across all DB types (even the new weird ones). However you still have to get method name correct, complex queries look well complicated and you need a specific repository for each entity.

If those extra dependencies do not appeal you could copy and paste a generic dao/repository (just googling provides ample of examples) and extend it where necessary for each of your specific entity types.

Or of course you can do it the old fashioned way – not making use of @Entity and just populate your domain objects or DTOs with sql statements and a jdbc connection. Spring again provides some help for this with jdbcTemplate and rowMapper.

That is the current state of play afaik for ORM and persistence with java, JPA and spring.

I’ll post my own attempt at an improved generic repository which itself will be a facade/adapter/wrapper for JPA and criteria in the future (if I ever get around to doing it that is). The design will be focussed on simplicity, hitting the pareto principal for use cases, and providing one only generic repository with no subclassing required for different entities.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: