About this section
This exercise section is about how to work with Spring Data JPA
.
Below is a table with
- a topic to work on and
- a git branch with a particular exercise to checkout
The topics are in the suggested order for the exercises:
Topic | Git branch | Link to an article/Javadoc |
---|---|---|
Create some @Query Methods | data_query-methods-ex | spring.io |
Create some Derived Query Methods | data_derived-query-methods-ex | spring.io |
Additional resources
Spring data
Spring Data is a module of the Spring Framework that provides a set of tools and abstractions
for working with data in a database.
Spring Data makes it easier to work with databases
by providing a common interface for working with different data stores,
including relational databases, NoSQL databases, and others.
One of the key components of Spring Data is the Repository
interface.
A Repository provides a high-level abstraction for working with data in a database.
It defines a set of methods for creating, reading, updating, and deleting data, and also provides support for querying the data store.
Here's an example of how to define a Repository interface for working with a User entity in a relational database using Spring Data JPA:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByLastName(String lastName);
}
In this example, the UserRepository
interface extends the JpaRepository
interface,
which is a subinterface of Spring Data's Repository
interface.
The User
class represents a database entity, and Long
is the type of the entity's primary key.
The findByLastName
method is a custom query method that uses Spring Data's method naming convention to generate a query
that returns all User
entities with the specified last name. This method provides a convenient way to retrieve data from
the database without having to write custom SQL queries.
To use the UserRepository in a Spring application, you can inject it into a service or controller using Spring's @Autowired annotation:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsersByLastName(String lastName) {
return userRepository.findByLastName(lastName);
}
}
In the above example, the UserService
class uses the UserRepository
to retrieve a list of users by their last name.
This service can then be used by a controller to handle requests from a client.