Creating Spring Boot MVC application with AWS DynamoDB in 10 mins

Image
AWS DynamoDB DB is a serverless NOSQL database. You can understand how to build a spring boot Java web MVC application (Game Leaderboard) reading a AWS DynamoDB in 10 mins. Source of the demo code: https://github.com/babysteps-topro/spring-mvc-dynamodb Command to run the project: mvn spring-boot:run Video explain the table design: https://youtu.be/V0GtrBfY7XM Prerequisite: Install the AWS CLI: https://youtu.be/pE-Q_4YXlR0 Video explain the how to create the table: https://youtu.be/sBZIVLlmpxY

Customizing Spring Data JPA Repository

Spring Data is a very convenient library. However, as the project as quite new, it is not well featured. By default, Spring Data JPA will provide implementation of the DAO based on SimpleJpaRepository. In recent project, I have developed a customize repository base class so that I could add more features on it. You could add vendor specific features to this repository base class as you like.

Configuration
You have to add the following configuration to you spring beans configuration file. You have to specified a new repository factory class. We will develop the class later.


<jpa:repositories base-package="example.borislam.dao" 
factory-class="example.borislam.data.springData.DefaultRepositoryFactoryBean/>



Just develop an interface extending JpaRepository. You should remember to annotate it with @NoRepositoryBean.



@NoRepositoryBean
public interface GenericRepository <T, ID extends Serializable> 
 extends JpaRepository<T, ID> {    
}



Define Custom repository base implementation class
Next step is to develop the customized base repository class. You can see that I just one property (i.e. springDataRepositoryInterface) inside this customized base repository. I just want to get more control on the behaviour of the customized behaviour of the repository interface. I will show how to add more features of this base repository class in the next post.





import static org.springframework.data.jpa.repository.query.QueryUtils.toOrders;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaEntityInformationSupport;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.util.Assert;

@SuppressWarnings("unchecked")
@NoRepositoryBean
public class GenericRepositoryImpl<T, ID extends Serializable> 
 extends SimpleJpaRepository<T, ID>  implements GenericRepository<T, ID> , Serializable{
 
 private static final long serialVersionUID = 1L;

 static Logger logger = Logger.getLogger(GenericRepositoryImpl.class);
 
    private final JpaEntityInformation<T, ?> entityInformation;
    private final EntityManager em;
    private final DefaultPersistenceProvider provider;
     
    private  Class<?> springDataRepositoryInterface; 
 public Class<?> getSpringDataRepositoryInterface() {
  return springDataRepositoryInterface;
 }

 public void setSpringDataRepositoryInterface(
   Class<?> springDataRepositoryInterface) {
  this.springDataRepositoryInterface = springDataRepositoryInterface;
 }

 /**
     * Creates a new {@link SimpleJpaRepository} to manage objects of the given
     * {@link JpaEntityInformation}.
     * 
     * @param entityInformation
     * @param entityManager
     */
    public GenericRepositoryImpl (JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager , Class<?> springDataRepositoryInterface) {
     super(entityInformation, entityManager);
     this.entityInformation = entityInformation;
     this.em = entityManager;
     this.provider = DefaultPersistenceProvider.fromEntityManager(entityManager);
     this.springDataRepositoryInterface = springDataRepositoryInterface;
     }

    /**
     * Creates a new {@link SimpleJpaRepository} to manage objects of the given
     * domain type.
     * 
     * @param domainClass
     * @param em
     */
    public GenericRepositoryImpl(Class<T> domainClass, EntityManager em) {
        this(JpaEntityInformationSupport.getMetadata(domainClass, em), em, null);  
    }
 
    public <S extends T> S save(S entity)
    {     
        if (this.entityInformation.isNew(entity)) {
            this.em.persist(entity);
            flush();
            return entity;
          }
  entity = this.em.merge(entity);
  flush();
        return entity;
    }

   
    public T saveWithoutFlush(T entity)
    {
      return 
       super.save(entity);
    }
    
    public List<T> saveWithoutFlush(Iterable<? extends T> entities)
    {
     List<T> result = new ArrayList<T>();
  if (entities == null) {
   return result;
  }

  for (T entity : entities) {
   result.add(saveWithoutFlush(entity));
  }
  return result;
    }
} 





import static org.springframework.data.jpa.repository.utils.JpaClassUtils.isEntityManagerOfType;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.spi.PersistenceProvider;

import org.hibernate.ejb.HibernateQuery;
import org.springframework.data.jpa.repository.query.QueryExtractor;

/**
* 
* @author Boris lam
* This class is use when you use  DefaultRepositoryFactory to override default repository factory class.
* 
*/

public enum DefaultPersistenceProvider implements QueryExtractor, Serializable{

/**
* Hibernate persistence provider.
*/
HIBERNATE("org.hibernate.ejb.HibernateEntityManager") {

public String extractQueryString(Query query) {

return ((HibernateQuery) query).getHibernateQuery()
.getQueryString();
}


/**
* Return custom placeholder ({@code *}) as Hibernate does create
* invalid queries for count queries for objects with compound keys.
* 
* @see HHH-4044
* @see HHH-3096
*/
@Override
protected String getCountQueryPlaceholder() {

return "*";
}
},

/**
* EclipseLink persistence provider.
*/
ECLIPSELINK("org.eclipse.persistence.jpa.JpaEntityManager") {

public String extractQueryString(Query query) {
//return ((JpaQuery<?>) query).getDatabaseQuery().getJPQLString();
return null;
}

},

/**
* OpenJpa persistence provider.
*/
OPEN_JPA("org.apache.openjpa.persistence.OpenJPAEntityManager") {

public String extractQueryString(Query query) {
//return ((OpenJPAQuery) query).getQueryString();
return null;
}
},

/**
* Unknown special provider. Use standard JPA.
*/
GENERIC_JPA("javax.persistence.EntityManager") {

public String extractQueryString(Query query) {

return null;
}


@Override
public boolean canExtractQuery() {

return false;
}
};

private String entityManagerClassName;


/**
* Creates a new {@link PersistenceProvider}.
* 
* @param entityManagerClassName the name of the provider specific
*            {@link EntityManager} implementation
*/
private DefaultPersistenceProvider(String entityManagerClassName) {

this.entityManagerClassName = entityManagerClassName;
}


/**
* Determines the {@link PersistenceProvider} from the given
* {@link EntityManager}. If no special one can be determined
* {@value #GENERIC_JPA} will be returned.
* 
* @param em
* @return
*/
public static DefaultPersistenceProvider fromEntityManager(EntityManager em) {

for (DefaultPersistenceProvider provider : values()) {
if (isEntityManagerOfType(em, provider.entityManagerClassName)) {
return provider;
}
}

return GENERIC_JPA;
}


/*
* (non-Javadoc)
* 
* @see
* org.springframework.data.jpa.repository.query.QueryExtractor#canExtractQuery
* ()
*/
public boolean canExtractQuery() {

return true;
}


/**
* Returns the placeholder to be used for simple count queries. Default
* implementation returns {@code *}.
* 
* @return
*/
protected String getCountQueryPlaceholder() {

return "x";
}

}



As a simple example here, I just override the default save method of the SimpleJPARepository. The default behaviour of the save method will not flush after persist. I modified to make it flush after persist. On the other hand, I add another method called saveWithoutFlush() to allow developer to call save the entity without flush. 

Define Custom repository factory bean
The last step is to create a factory bean class and factory class to produce repository based on your customized base repository class.



import java.io.Serializable;
import javax.persistence.EntityManager;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

public class DefaultRepositoryFactoryBean <T extends JpaRepository<S, ID>, S, ID extends Serializable>
  extends JpaRepositoryFactoryBean<T, S, ID> {
    /**
     * Returns a {@link RepositoryFactorySupport}.
     * 
     * @param entityManager
     * @return
     */
    protected RepositoryFactorySupport createRepositoryFactory(
            EntityManager entityManager) {

        return new DefaultRepositoryFactory(entityManager);
    }
}


/**
 * 
 * The purpose of this class is to override the default behaviour of the spring JpaRepositoryFactory class.
 * It will produce a GenericRepositoryImpl object instead of SimpleJpaRepository. 
 * 
 */

import static org.springframework.data.querydsl.QueryDslUtils.QUERY_DSL_PRESENT;

import java.io.Serializable;
import javax.persistence.EntityManager;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.query.QueryExtractor;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.QueryDslJpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.util.Assert;


public  class DefaultRepositoryFactory extends JpaRepositoryFactory{
    
 private final EntityManager entityManager;
    private final QueryExtractor extractor;


    public DefaultRepositoryFactory(EntityManager entityManager) {
     super(entityManager);
        Assert.notNull(entityManager);
        this.entityManager = entityManager;
        this.extractor = DefaultPersistenceProvider.fromEntityManager(entityManager);
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected <T, ID extends Serializable> JpaRepository<?, ?> getTargetRepository(
            RepositoryMetadata metadata, EntityManager entityManager) {

        Class<?> repositoryInterface = metadata.getRepositoryInterface();
       
        JpaEntityInformation<?, Serializable> entityInformation =
                getEntityInformation(metadata.getDomainType());

        if (isQueryDslExecutor(repositoryInterface)) {
            return new QueryDslJpaRepository(entityInformation, entityManager);
        } else {
            return new GenericRepositoryImpl(entityInformation, entityManager, repositoryInterface); //custom implementation
        }
    }
 
    @Override
    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {

        if (isQueryDslExecutor(metadata.getRepositoryInterface())) {
            return QueryDslJpaRepository.class;
        } else {
            return GenericRepositoryImpl.class;
        }
    }
    
    /**
     * Returns whether the given repository interface requires a QueryDsl
     * specific implementation to be chosen.
     * 
     * @param repositoryInterface
     * @return
     */
    private boolean isQueryDslExecutor(Class<?> repositoryInterface) {

        return QUERY_DSL_PRESENT
                && QueryDslPredicateExecutor.class
                        .isAssignableFrom(repositoryInterface);
    }   
}






Conclusion
You could now add more features to base repository class. In your program, you could now create your own repository interface extending GenericRepository instead of JpaRepository.


public interface MyRepository <T, ID extends Serializable>
  extends GenericRepository <T, ID> {
   void someCustomMethod(ID id);  
}


In next post, I will show you how to add hibernate filter features to this GenericRepository.


There is another reference for Spring data from Java code Geek:
https://examples.javacodegeeks.com/spring-data-jpa-example/

Comments

Unknown said…
Did you see any jar file DefaultPersistenceProvider?
Unknown said…
This comment has been removed by the author.
Unknown said…
where does this come from QUERY_DSL_PRESENT
Boris Lam said…
QUERY_DSL_PRESENT come from :

org.springframework.data.querydsl.QueryDslUtils.QUERY_DSL_PRESENT;
Boris Lam said…
I have put the source code of DefaultPersistenceProvider.java back
dropdeadfred said…
Am I correct in assuming this only allows you to override behavior in existing SimpleJpaRepository methods?
To add additional query methods to your repositories, would they need to extend the new GenericRepository interface where addtional methods could be defined and implemented in the GenericRepositoryImpl?
Unknown said…
Can I use PersistenceProvider instead of DefaultPersistenceProvider? I saw you changed ECLIPSELINK and OPEN_JPA to null. What's your purpose for this? Thanks a lot!
Unknown said…
Your post is exact what I need. Thanks very much for sharing this useful information. BTW, the save(S) in GenericRepositoryImpl cannot be compile
Unknown said…
This comment has been removed by the author.
ko said…
i'm trying to do soemthing simmilar to your example, but i can't get it work. In case you could give me a hand here is an example code https://dl.dropboxusercontent.com/u/11115278/src-spring-problem/SpringSimple.zip.renameit
ko said…
i'm trying to do soemthing simmilar to your example, but i can't get it work. In case you could give me a hand here is an example code https://dl.dropboxusercontent.com/u/11115278/src-spring-problem/SpringSimple.zip.renameit
Unknown said…
I have linked your post on the this so Question http://stackoverflow.com/questions/30430187/filters-for-spring-data-jpa/30451988#30451988. This post led me to a solution to the question. Nice post!!!!
AnkitP said…
getting following error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object

Please help!
fxtestx said…
How do I set factory-class with CDI?

Popular posts from this blog

Sample Apps: Spring data MongoDB and JSF Integration tutorial (PART 1)

Adding Hibernate Entity Level Filtering feature to Spring Data JPA Repository