Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the repository from the entity in Spring Boot?

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

like image 643
pupeno Avatar asked Sep 07 '17 09:09

pupeno


People also ask

How do I access EntityManager in spring boot?

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.


1 Answers

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.

like image 126
David Avatar answered Oct 20 '22 19:10

David