Simpler JPA with Spring Data-JPA

How to configure your Spring application with Simple CRUD configuration with Spring Data-JPA.



1. Add Spring Data-JPA to project configuration. In your Maven pom.xml file

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>1.2.0.RELEASE</version>
</dependency>



2. Configure JPA Entity

...

@Entity
public class Product {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id")
  private Long id;

  @NotNull
  @Column(unique = true)
  private String productId;

  @NotNull
  private Integer quantity;

  ... 
}



3. Configure Typed Repository Interface

Spring Data JPA will create the beans for us.

package com.gordondickens.myapp.repository;

import org.springframework.data.repository.CrudRepository;
import com.gordondickens.myapp.entity.Product;

public interface ProductRepository 
   extends CrudRepository<Product, Long> {}



4. Configure the application context

Note: this example uses Hibernate and HSQL

<!-- Directory to scan for repository classes -->
<jpa:repositories 
   base-package="com.gordondickens.myapp.repository" />

<bean class="org.springframework.orm.jpa.JpaTransactionManager"
  id="transactionManager">
  <property name="entityManagerFactory" 
      ref="entityManagerFactory" />
  <property name="jpaDialect">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
  </property>
</bean>

<bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
      <property name="generateDdl" value="true" />
      <property name="database" value="HSQL" />
    </bean>
  </property>
</bean>



5. Inject the Repository

In our service class & tests we use the repository to execute our crud methods. Repository Methods: count(), exists(), delete(), deleteAll(), findOne(), findAll(), save().

public class ProductServiceImpl extends ProductService {

   @Autowired
   ProductRepository productRepository;

  ...
}

See Part 2 – Adding Queries to Spring Data-JPA



Summary

The Spring Data project abstracts away basic data management concepts. In addition to support for traditional relational methodologies, Spring Data provides support for NoSQL Graph, Key-Value and Map-Reduce types. As we saw in the above example configuring CRUD style applications is fairly trivial and Spring provides a convenient configuration for the typical cookie cutter code.

Click here to see my other blog which lists the annotations in “Spring Data-Commons” and “Spring Data-JPA”.

About Gordon

Technology enthusiast primarily focused on Java and Open Source projects. Spring Certified Professional and Trainer. http://twitter.com/gdickens http://linkedin.com/in/gordondickens http://github.com/gordonad
This entry was posted in Hibernate, JPA, Spring, Spring Data, Spring Framework and tagged , , , , , , . Bookmark the permalink.

12 Responses to Simpler JPA with Spring Data-JPA

  1. Pingback: Technophile Blog » Adding Queries to Spring Data-JPA

  2. Joao says:

    Where is the class definition for ProductService? Am I missing something?

  3. Gordon says:

    You simply create the Service class as you would any other… in src/main/java under your package for example com.chariotsolutions.myproject.services
    ProductService.java interface and create the subclass ProductServiceImpl.java implementing ProductService.java.

    Regards,
    Gordon Dickens

  4. Is the source code available? Would be nice to have it on github or any other place.

  5. supra says:

    Is it possible this example are refactoring to utilize hibernate entities mapping in *.hbm.xml? We have application with many hibernate and have plan to use Spring Data JPA. We will appreciate if you could give us simple example for that.

  6. Gordon says:

    Hi Supra,

    I do not have any examples handy for JPA2 and Hibernate with *.hbm.xml files. Since this is using standard JPA2, there should be good resources available on the web.

  7. Markus Fried says:

    perfect tutorial for people without JPA experience like me ;-)

    I stumbled over one thing: I wrote a JUnit test case for the ServiceImpl-Class running against an Oracle database. Within Eclipse all went well, but trying to run the tests from outside (Ant or Gradle in my situation) gave


    FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Not an entity: class ...

    To overcome this I had to add the entity class to the persistence.xml file.

    Now I’m confused: why do I tag the class with @entity AND add it to the persistence.xml?

    Have you ever experienced this, too?

    Best regards
    Mark.

  8. Gordon says:

    I have not had that experience. It sounds like it might be an issue of dependency versions between the different environments. Are any of your build dependencies marked as “provided” where they are expected on the server platform? Those would be the primary suspects.

  9. GJay says:

    I get a

    “org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.acme.repository.AcmeRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} ”

    while loading the app. Is there any other configuration step that I am missing ?

  10. Gordon says:

    GJay, As long as your repository classes are available via explicit declaration or component-scan, it should be found. Component scan can be a bit tricky, the inner include/exclude tags can cause classes to be skipped. Let me know if you are still stuck, more of the example might be helpful.

    See my git repo for ORM demos here: https://github.com/gordonad/core-spring-demos/tree/master/demos/orms

    Regards,
    Gordon

  11. Stephane says:

    I’m surprised to see a: extends ProductService instead of an: implements ProductService

  12. henry harles says:

    Can you just provide the spring data jpa small application
    Examlle using xml configuration only not with @autowire over repository it should be injected only with xml only

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>