Reputation: 640
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?
Upvotes: 17
Views: 20988
Reputation: 11
If you want to use your interface, you can do something similar.
UserRepository
) and extends SimpleJpaRepository
.private static class SimpleUserRepository<T, ID> extends SimpleJpaRepository<T, ID> implements UserRepository<T, ID> {
public SimpleIRepository(Class<T> domainClass, EntityManager em) {
super(domainClass, em);
}
}
JpaRepository
.UserRepository<User, Long> userRepository = new SimpleUserRepository<>(User.class, em);
UserRepository
interface.userRepository.save(user);
Upvotes: 0
Reputation: 2267
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
Upvotes: 6
Reputation: 640
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);
Upvotes: 21