如何在类中动态创建Jpa存储库? [英] How to create Jpa repository dynamically inside a class?

查看:125
本文介绍了如何在类中动态创建Jpa存储库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在类中创建和实例化jpa存储库?我遇到的情况是我必须为泛型类中的不同实体创建存储库。

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.

我可以轻松地为Neo4j存储库这样做,

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); 

对于JpaRepository,我检查了文档并找到了这个,

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.

我也不能通过指定域类来创建像Neo4j那样的存储库吗?

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

推荐答案

我终于以这种方式工作了,

I finally got it working this way,

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

使用SimpleJpaRepository,我可以使用所有存储库方法。

With SimpleJpaRepository, I can use all repository methods.

jpaRepository.save(user);

这篇关于如何在类中动态创建Jpa存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆