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

查看:19
本文介绍了如何在类中动态创建 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?

推荐答案

我终于可以这样了,

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天全站免登陆