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;
How can I get hold of the repository in a method in the Account class? I tried @Autowired but it didn't work.
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
The complete example of getting EntityManager using the custom configuration in Spring Boot. Open eclipse and create maven project, Don't forget to check 'Create a simple project (skip)'click on next. Fill all details(GroupId – entitymanager, ArtifactId – entitymanager and name – entitymanager) and click on finish.
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;
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 {
Thanks to Christian Kaspari who is author of this repository.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With