如何在Spring Boot中从实体访问存储库? [英] How can I access the repository from the entity in Spring Boot?
问题描述
在Spring Boot项目中,我有一个JPA实体,如下所示:
In a Spring Boot project I have a JPA entity, like this:
@Entity
public class Account {
}
然后我有了用于查询数据库的存储库:
and then I have the repository to query the database:
public interface AccountRepository extends JpaRepository<Account, UUID> {
}
在应用程序和测试中,通过执行以下操作很容易获得存储库:
In both the app and tests it's easy to get the repository by doing:
@Autowired
private AccountRepository accountRepository;
如何在Account类的方法中控制存储库?我尝试了@Autowired,但是没有用.
How can I get hold of the repository in a method in the Account class? I tried @Autowired but it didn't work.
对于那些争论设计的人,我的问题不关乎设计.我已经用Ruby和Rails以及用HugSQL编写的Clojure编写了这段代码,并且它是自包含的和简洁的:创建新记录时,我还生成了一个紧凑的唯一字母数字ID.在Ruby on Rails中,我将其作为库发布: https://github.com/pupeno/random_unique_id
For those arguing about design, my question is not about design. I have written this code in Ruby and Rails as well as Clojure with HugSQL and it was self contained and concise: when creating a new record I also generate a compact unique alphanumeric id. In Ruby on Rails I released it as a library: https://github.com/pupeno/random_unique_id
推荐答案
我有同样的问题,发现此Github存储库.
I had same question and found this Github repository.
以下是代码的某些部分:
Here are some parts of code:
...
import de.ck35.example.ddd.jpa.SpringEntityListener;
...
@Entity
@Table(name="bookshelf")
@EntityListeners(SpringEntityListener.class)
public class BookshelfEntity implements Bookshelf {
...
private String category;
@Autowired transient BookRepository bookRepository;
@Autowired transient BookshelfSpaceRepository bookshelfSpaceRepository;
在 Javadoc
中描述了 de.ck35.example.ddd.jpa.SpringEntityListener
目的的位置:
Where de.ck35.example.ddd.jpa.SpringEntityListener
purpose is described in Javadoc
:
/**
* Entity listener which allows dependency injection inside entities.
* The listener can be registered via {@link EntityListeners} annotation.
*
* Dependency injection annotations like {@link Autowired} are supported.
*
* @author Christian Kaspari
* @since 1.0.0
*/
public class SpringEntityListener {
...
@PostLoad
@PostPersist
public void inject(Object object) {
AutowireCapableBeanFactory beanFactory = get().getBeanFactory();
if(beanFactory == null) {
LOG.warn("Bean Factory not set! Depdendencies will not be injected into: '{}'", object);
return;
}
LOG.debug("Injecting dependencies into entity: '{}'.", object);
beanFactory.autowireBean(object);
}
还有一种配置可以启用嵌套在类(在本例中为实体)中的存储库定义:
There is also configuration which enables Repositories definitions nested in classes (in this case entities):
@Configuration
@EnableJpaRepositories(basePackages="de.ck35.example.ddd.jpa", considerNestedRepositories=true)
@ComponentScan("de.ck35.example.ddd.jpa")
public class JpaConfiguration {
感谢此存储库的作者 Christian Kaspari .
这篇关于如何在Spring Boot中从实体访问存储库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!