Posts Tagged ‘jpa’
  • Easier JPA with Spring Data JPA

    Database access in Java went through some steps:

    • at first, pure JDBC
    • proprietary frameworks
    • standards such as EJB Entities and JDO
    • OpenSource frameworks such as Hibernate and EclipseLink (known as TopLink at the time)

    When JPA was finally released, it seemed my wishes came true. At last, there was a standard coming from the trenches to access databases in Java

    Unfortunately, JPA didn’t hold its promises when compared to Hibernate: for example, you don’t have Query by Example. Even worse, in its first version, JPA didn’t provide simple features like Criteria, so that even simple queries would have to be implemented through JPQL and thus achieved with String concatenation. IMHO, this completely defeated ORM purposes.

    JPA2 to the rescue

    At last, JPA2 supplies something usable in a real-world application. And yet, I feel there’s still so much boilerplate code to write a simple CRUD DAO:

    public class JpaDao {
        private EntityManager em;
        private Class managedClass;
        private JpaDao(Class managedClass) {
            this.managedClass = managedClass;
        public void persist(E entity) {
        public void remove(E entity) {
        public E findById(PK id) {
            return em.find(managedClass, id);

    Some would (and do) object that in such a use-case, there’s no need for a DAO: the EntityManager just needs to be injected in the service class and used directly. This may be a relevant point-of-view, but only when there’s no query for as soon as you go beyond that, you need to separate between data access and business logic.

    Boilerplate code in JPA2

    Two simple use-cases highlight the useless boilerplate code in JPA 2: @NamedQuery and simple criteria queries. In the first case, you have to get the handle on the named query through the entity manager, then set potential parameters like so:

    Query query = em.createNamedQuery("Employee.findHighestPaidEmployee");

    In the second, you have to implement your own query with the CriteriaBuilder:

    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery query = builder.createQuery(Person.class);
    Root fromPerson = query.from(Person.class);
    return em.createQuery(;

    IMHO, these lines of code bring nothing to the table and just clutter our own code. By chance, some time ago, I found project Hades, a product which was based on this conclusion and wrote simple code for you.

    Spring Data JPA

    Given the fate of some excellent OpenSource projects, Hades fared much better since it has been brought into the Spring ecosystem under the name Spring Data JPA. Out of the box, SDJ provides DAOs that have advanced CRUD features. For example, the following interface can be used as-is:

    public interface EmployeeRepository extends JPARepository

    Given some Spring magic, an implementation will be provided at runtime with the following methods:

    • void deleteAllInBatch()
    • void deleteInBatch(Iterable<Employee> entities)
    • List<Employee> findAll()
    • List<Employee> findAll(Sort sort)
    • void flush()
    • <S extends Employee> List<S> save(Iterable<S> entities)
    • Employee saveAndFlush(Employee entity)
    • Page<Employee> findAll(Pageable pageable)
    • Iterable<Employee> findAll(Sort sort)
    • long count()
    • void delete(ID id)
    • void delete(Iterable<? extends Employee> entities)
    • void delete(Employee entity)
    • void deleteAll()
    • boolean exists(Long id)
    • Iterable<Employee> findAll()
    • Iterable<Employee> findAll(Iterable ids)
    • Employee findOne(Long id)
    • <S extends Employee> Iterable<S> save(Iterable<S> entities)
    • <S extends Employee> S save(S entity)

    Yes, SDJ provides you with a generic DAO, like so many frameworks around but here, wiring into the underlying implementation is handled by the framework, free of charge. For those that don’t need them all and prefer the strict minimum, you can also use the following strategy, where you have to choose the methods from the list above (and use the annotation):

    @RepositoryDefinition(domainClass = Employee.class, idClass = Long.class)
    public interface EmployeeRepository {
        long count();
        Employee save(Employee employee);

    It sure is nice, but the best is yet to come. Remember the two above use-cases we had to write on our own? The first is simply handled by adding the unqualified query name to the interface like so:

    @RepositoryDefinition(domainClass = Employee.class, idClass = Long.class)
    public interface EmployeeRepository {
        Employee findHighestPaidEmployee();

    The second use-case, finding all employees, is provided in the JPA repository. But let’s pretend for a second we have a WHERE clause, for example on the first name. SDJ is capable of handling simple queries based on the method name:

    @RepositoryDefinition(domainClass = Employee.class, idClass = Long.class)
    public interface EmployeeRepository {
        List findByLastname(String firstName);

    We had to code only an interface and its methods: no implementation code nor metamodel generation was involved! Don’t worry, if you need to implement some complex queries, SDJ let you wire your own implementation.


    If you’re already a Spring user, Spring Data JPA is really (really!) a must. If you’re not, you’re welcome to test it to see its added value by yourself. IMHO, SDJ is one of the reason JavaEE has not killed Spring yet: it bridged the injection part, but the boilerplate code is still around every corner.

    This article is not a how-to but a teaser to let you into SDJ. You can find the sources for this article here, in Maven/Eclipse format.

    To go further:

    For those that aren’t into JPA yet, there’s Data JDBC; for those that are well beyond that (think Big Data); there’s a Data Hadoop. Check all of Spring Data projects!

    Categories: Java Tags: jpapersistencespring data
  • Hibernate hard facts - Part 4

    In the fourth article of this serie, I will show the subtle differences between get() and load() methods.

    Hibernate, like life, can be full of suprises. Today, I will share one with you: have you ever noticed that Hibernate provides you with 2 methods to load a persistent entity from the database tier? These two methods are get(Class, Serializable) and load(Class, Serializable) of the Session class and their respective variations.

    Strangely enough, they both have the same signature. Strangely enough, both of their API description starts the same:

    Return the persistent instance of the given entity class with the given identifier.

    Most developers use them indifferently. It is a mistake since, if the entity is not found, get() will return null when load() will throw an Hibernate exception. This is well described in the API:

    Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists. You should not use this method to determine if an instance exists (use get() instead). Use this only to retrieve an instance that you assume exists, where non-existence would be an actual error.

    Truth be told, the real difference lies elsewhere: the get() method returns an instance, whereas the load() method returns a proxy. Not convinced? Try the following code snippet:

    Session session = factory.getCurrentSession();
    Owner owner = (Owner) session.get(Owner.class, 1);
    // Test the class of the object
    assertSame(owner.getClass(), Owner.class);

    The test pass, asserting that the owner’s class is in fact Owner. Now, in another session, try the following:

    Session session = factory.getCurrentSession();
    Owner owner = (Owner) session.load(Owner.class, 1);
    // Test the class of the object
    assertNotSame(owner.getClass(), Owner.class);

    The test will pass too, asserting that the owner’s class is not Owner. If you spy the object in the debugger, you’ll see a Javassist proxyed instance and that fields are not initialized! Notice that in both cases, you are able to safely cast the instance to Owner. Calling getters will also return expected results.

    Why call the load() method then? Because since it is a proxy, it won’t hit the DB until a getter method is called.

    Moreover, these features are also available in JPA from the EntityManager, respectively with the find() and getReference() methods.

    Yet, both behaviours are modified by Hibernate’s caching mechanism. Try the following code snippet:

    // Loads the reference
    session.load(Owner.class, 1);
    Owner owner = (Owner) session.get(Owner.class, 1);

    According to what was said before, owner’s real class should be the real McCoy. Dead wrong! Since Hibernate previously called load(), the get() looks in the Session cache (the 1st level one) and returns a proxy!

    The behaviour is symmetrical with the following test, which will pass although it’s counter-intuitive:

    // Gets the object
    session.get(Owner.class, 1);
    // Loads the reference, but looks for it in the cache and loads
    // the real entity instead
    Owner owner = (Owner) session.load(Owner.class, 1);
    // Test the class of the object
    assertSame(owner.getClass(), Owner.class);

    Conclusion: Hibernate does a wonderful job at making ORM easier. Yet, it’s not an easy framework: be very wary for subtle behaviour differences.

    The sources for the entire hard facts serie is available here in Eclipse/Maven format.

    Categories: Java Tags: gethibernatejpaloadproxy
  • Framework agnostic JPA

    With new JEE 5 standard has come the EJB3 specifications. From an historical point of view, EJBs come into 3 different flavors: (i) Entity for persistence, (ii) Session for business logic and (iii) Message-Driven for listeners. Entity EJB are the most time-consuming to develop in their 2.1 version. Apart from the inherent complexity of EJB (local and remote interfaces, homes), developing an EJB 2 is error-prone because of the mapping mechanism. All in all, EJB 2 development really needs a very specialized IDE and expert developers. That’s the main reason why EJB 2 didn’t achieve a significant market share, and had to compete with JDO, Hibernate and other third-party frameworks.

    Sun eventually realized this and did come with a much simpler solution with EJB 3. Using Java 5 annotations, developing Entity EJB 3 is a breeze. The part of EJB 3 specifications that deal with Entity is called Java Persistence API (JPA). It is a specification in its own right, and in the next specifications, it will have its own. Developing JPA applications is a two-step process. First, you have to create you model classes. Such classes will be the foundation of your persistence layer: it would be a good idea to use this layer throughout your entire organization, since these classes should closely map your database model. A simple JPA enhanced class would look like this:

    import static javax.persistence.GenerationType.IDENTITY;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    public class Book implements Serializable {
        /** Unique class's serial version identifier. */
        private static final long serialVersionUID = 7292903017883188330L;
        /** Book's unique identifier. */
        @GeneratedValue(strategy = IDENTITY)
        private long id;
        /** ISBN. */
        private String isbn;
        /** Book's title. */
        private String title;
        /** Publication's date. */
        private Date published;
        public long getId() {
            return id;
        public String getIsbn() {
            return isbn;
        public Date getPublished() {
            return published;
        public String getTitle() {
            return title;
        public void setId(long aId) {
            id = aId;
        public void setIsbn(String aIsbn) {
            isbn = aIsbn;
        public void setPublished(Date aPublished) {
            published = aPublished;
        public void setTitle(String aTitle) {
            title = aTitle;

    You have noticed 3 annotations:

    • javax.persistence.Entity (line 9): just this annotation enables your model's class to be used by JPA,
    • javax.persistence.Id (line 16): identifies the primary key column,
    • javax.persistence.GeneratedValue (line 17): how to generate PK while inserting.

    Mapping your classes against the database is the most important operation of JPA. It is out of the scope of this article, suffice to say the least is you can do is use the 3 above annotations.

    If you’re using Eclipse, and if you don’t want to learn all JPA annotations, I recommend using JPA facet. Just righ-click your project, select Properties and go to Project Facets. Then select Java Persistence. Apart from creating needed configuration files (see below) and providing a nice utility view for them, it allows two more views for each of you model classes:

    • JPA Structure which should map your database structure,
    • JPA Details where you can add and change JPA annotations.

    JPA details in Eclipse

    Once mapping is done, either through brute force or the neat little wizard provided just above, how can you CRUD theses entities? First, you can continue using your favorite JPA-compatible persistence framework. In my case, I use Hibernate, which happens to be JPA reference implementation. The following code is called once, preferably in an utility class:

    AnnotationConfiguration configuration = new AnnotationConfiguration();
    sessionFactory = configuration.buildSessionFactory();

    Now you only have to get the session for every unit-of-work and use it in your DAO:

    Session session = sessionFactory.getSession();
    // Get every book in database
    List books = session.createCriteria(Book.class).list();

    Now we got model’s classes that are Hibernate independent but our DAOs are not. Since using JPA API instead of Hibernate API decouples our code from the underlying framework, and this at no significant performance cost, it becomes highly desirable to remove this dependency. You need to have :

    • a compile-time dependency to ejb3-persistence.jar,
    • a runtime dependency to hibernate-entitymanager.jar or its TopLink equivalent. Transitive dependencies are of course framework dependent.

    JPA configuration is done through 2 files:

    • META-INF/orm.xml for mapping informations. In our case, it is already done with annotations.
    • META-INF/persistence.xml for meta information, e.g JNDI location of the datasource to use.

    When done, the calling sequence is very similar to Hibernate’s:

    // This done once per application
    // Notice its similitude with Hibernate's SessionFactory
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("myManager");
    // This done per unit of work
    // Notice its similitude with Hibernate's Session
    EntityManager em = emf.createEntityManager();
    // Get every book in database
    List books = em.createQuery("SELECT b FROM Book").getResultList();

    Now, using the above code, passing from an Hibernate implementation to a TopLink implementation is transparent. Just remove Hibernate JARs and put TopLink JARs on the runtime classpath.

    Categories: Java Tags: hibernatejpapersistence