I'm looking for information about how to configure Spring Data JDBC in a Spring Boot app (a Gradle example would be ideal).
I've read through the docs , and I know that I need to define a Repository
implementation for each domain class (or "aggregate" of domain classes), eg
interface UserRepository extends CrudRepository<User, Long> {
// custom query methods
long countByLastname(String lastname);
}
But it's not entirely clear what dependencies need to be added, how to inject the repository beans into other beans, how to specify to Spring where the repository beans can be found, etc.
I'd particularly like to see how to define a repository that manages more than one table/domain class. For example a repository that manages persistence of an Order
and it's collection of OrderItem
s. The examples in the docs only show how to map a single domain class to a repository.
Since you're using Spring Boot to develop your application, you can leverage the starter Spring modules. In the specific case the dependency would be
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
The module version will be picked up automatically if you configured the Gradle Spring plugin
id 'org.springframework.boot' version '2.1.2.RELEASE' // Your version
When you create custom Repository
interfaces, you just need to annotate them with the class annotation @Repository
. The Spring-autoconfigured scanning mechanism will pick them up automatically (remember to place them in a sub-package, having the @SpringBootApplication
annotated class as root).
You can then @Autowire
your Repository in a Service, or whatever you want, using hopefully constructor injection.
@Autowired
MyClass(final MyRepository repository) { ... }
Note that if you have a single constructor, you don't need to specify the @Autowired
annotation.
Btw, the Data JDBC is a pretty new project. There are limitations, but I suppose you've found them in the Data JDBC documentation.
what dependencies need to be added
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
how to inject the repository beans into other beans
In your controller or service or any other bean, you can autowire this repository:-
private final UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
how to specify to Spring where the repository beans can be found
Spring Boot will automatically scan the package (and sub-packages) where you have your main class annotated with @SpringBootApplication
defined.
Also, annotate your interface with @Repository
:-
@Repository
interface UserRepository extends CrudRepository<User, Long> {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.