Suggested Pages

Monday, April 20, 2015

EJB with Spring Data Repository - Integration

In this post we are going see a very simple integration between a J2EE application and the Spring Data Framework.
Let us suppose to have the persistence layer written with Spring Data and we want to reuse the Spring Data Repository into a j2ee environment, for example in a Stateless EJB.
We can use the class JpaRepositoryFactory as shown below:
UserRepository.java

package com.simonefolinojavablog;

interface UserRepository extends Repository<User, Long> {
  ...
}
   

RepositoryAdapterBean.java

package com.simonefolinojavablog;

import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;

@Stateless(name="RepositoryAdapter")
public class RepositoryAdapterBean implements RepositoryAdapter{
  ...

 
  @PersistenceContext
  EntityManager entityManager;

  public User find(String userName){
       JpaRepositoryFactory jpaRepositoryFactory=new JpaRepositoryFactory(entityManager);
       UserRepository repository = jpaRepositoryFactory.getRepository(UserRepository.class);
       return repository.findOne(userName);

  }
}
   


You can use JpaRepositoryFactory with the EntityManager to create the UserRepository and make a reuse of all Spring Data components of the persistence layer.

No comments :

Post a Comment

Suggested Pages