Spring JpaRepository Example (In-Memory)

This post describes a simple Spring JpaRepository example using an in memory HSQL database. The code example is available from GitHub in the Spring-JpaRepository directory. It is based on the Spring-MVC-With-Annotations example and information available here.

JPA Repository

We implement a dummy bean for this example:

public class SomeItem {

    private long Id;

    private String someText;

    /* ...Setters & Getters */


and the corresponding JpaRepository:

public interface SomeItemRepository
        extends JpaRepository<SomeItem, Long> {


Service & Controller

Next, we implement a service where our repository will be injected. We also populate the repository with dummy data:

public class SomeItemService {

    private SomeItemRepository someItemRepository;

    public void populate() {

        SomeItem si = new SomeItem();

        si = new SomeItem();

        si = new SomeItem();


    public List<SomeItem> getAll() {

        return someItemRepository.findAll();


    public SomeItem saveAndFlush(SomeItem si) {

        if ( si != null ) {
            si = someItemRepository.saveAndFlush(si);

        return si;


    public void delete(long id) {




and a controller:

public class MyController {

    private SomeItemService someItemService;

    @RequestMapping(value = "/")
    public ModelAndView index() {

        ModelAndView result = new ModelAndView("index");
        result.addObject("items", this.someItemService.getAll());

        return result;


    @RequestMapping(value = "/delete/{id}")
    public String delete(
        @PathVariable(value="id") String id) {


        return "redirect:/";


    @RequestMapping(value = "/create")
    public String add() {

        SomeItem si = new SomeItem();
        si.setSomeText("Time is: " + System.currentTimeMillis());


        return "redirect:/";



JPA Configuration

On top of creating an entity manager based on an in-memeory instance of HSQL database, we enable JPA repositories with the
@EnableJpaRepositories annotation:

public class JpaConfig implements DisposableBean {

    private EmbeddedDatabase ed;

    public EmbeddedDatabase hsqlInMemory() {

        if ( this.ed == null ) {
            EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
            this.ed = builder.setType(EmbeddedDatabaseType.HSQL).build();

        return this.ed;


    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){

        LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

        lcemfb.setPackagesToScan(new String[] {"com.jverstry"});


        HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();

        Properties ps = new Properties();
        ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
        ps.put("hibernate.hbm2ddl.auto", "create");


        return lcemfb;


    public PlatformTransactionManager transactionManager(){

        JpaTransactionManager tm = new JpaTransactionManager();

            this.entityManagerFactory().getObject() );

        return tm;


    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();

    public void destroy() {

        if ( this.ed != null ) {



The JSP Page

We create a simple page to list existing items with a delete link, and the possibility to create new items:

 Running The Example

One can run it using the maven tomcat:run goal. Then, browse: http://localhost:9191/spring-jparepository/


Reference: Spring JpaRepository Example (In-Memory) from our JCG partner Jerome Versrynge at the Technical Notes blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Spring JpaRepository Example (In-Memory)"

  1. Boris says:

    I get java.lang.NullPointerException when I try to run metthods of interface in my case
    repo.findAll() where repo defined before as @Autowired
    GreetingRepo repo;

    Instance is null, Something miss here

Leave a Reply

1 × six =

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books