Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Jpa repository dynamically inside a class?

How do I create and instantiate a jpa repository inside a class? I'm in a situation where I have to create repositories for different entities inside a generic class.

I could do that easily for Neo4j repositories like,

GraphRepository<T> graphRepository;

this.neo4jTemplate = new Neo4jTemplate(new RestGraphDatabase(
    "http://localhost:7474/db/data"));
this.graphRepository = neo4jTemplate.repositoryFor(domainClass); 

For JpaRepository, I checked the documentation and found this,

RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);

I'm not sure how to instantiate factory in the above code.

Also Can't I create repository like I did for Neo4j, by specifying the domain class?

like image 885
Logesh G Avatar asked Mar 01 '14 15:03

Logesh G


People also ask

How JPA Repository works internally?

Spring then parses the method name and creates a query for it. Here is a simple example of a query that loads a Book entity with a given title. Internally, Spring generates a JPQL query based on the method name, sets the provided method parameters as bind parameter values, executes the query and returns the result.

Which is better CrudRepository or JpaRepository?

Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.


2 Answers

Using SimpleJpaRepository you can only use the default methods provided by interface but not what you declare in your UserRepository

If you wanted to create instance of interface of your UserRepository you can use -

RepositoryFactorySupport factory = new JpaRepositoryFactory(entityManager);
UserRepository repository = factory.getRepository(UserRepository.class);

it will give you liberty to use custom methods also that was defined by you in UserRepository

like image 125
Pankaj Sharma Avatar answered Sep 16 '22 18:09

Pankaj Sharma


I finally got it working this way,

SimpleJpaRepository<User, Serializable> jpaRepository;
jpaRepository = new SimpleJpaRepository<User, Serializable>(
    User.class, entityManager);

With SimpleJpaRepository, I can use all repository methods.

jpaRepository.save(user);
like image 21
Logesh G Avatar answered Sep 19 '22 18:09

Logesh G