In this tutorial, we will learn on Spring Data with CrudRepository Interface.
CrudRepository
interface in a Spring application:
User Entity:
@Table(name = "user")
@Entity
public class User {
@Id
@Column(name = "user_id")
private Long userId;
@Column(name="email")
private String email;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Create UserRepository class that should me marked with @Repository Annotation:
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
In this example, the UserRepository
interface is defined as extending the CrudRepository
interface, where User
is the entity class and Long
is the type of the primary key.
By extending CrudRepository
, the UserRepository
interface automatically gets a set of methods for performing CRUD operations on the User
entity. For example, you can use the save
method to save a new user to the repository, the findOne
method to retrieve a user by its primary key, and the delete
method to delete a user from the repository.
Create UserServiceImpl class that should be marked with @Service Annotation:
@Service public class UserServiceImpl { @Autowired private UserRepository userRepo; public void saveUser(User user) { userRepo.save(user); } public User getUser(Long userId) { return userRepo.findOne(userId); } public void deleteUser(Long userId) { userRepo.delete(userId); } }
In this example, we’re using the @Autowired
annotation to automatically wire an instance of the UserRepository
into our application, and then using the save
, findOne
, and delete
methods to perform CRUD operations on the repository.
CrudRepository Interface methods:
CrudRepository is a Spring Data interface that provides basic CRUD (Create, Read, Update, Delete) operations for a specific type of entity. The interface defines the following methods:
save(S entity)
: Saves a given entity. Returns the saved entity.saveAll(Iterable<S> entities)
: Saves all given entities. Returns a list of saved entities.findById(ID id)
: Retrieves an entity by its id. Returns an Optional.existsById(ID id)
: Returns true if an entity with the given id exists, false otherwise.findAll()
: Returns all entities.findAllById(Iterable<ID> ids)
: Returns all entities with the given ids.count()
: Returns the number of entities.deleteById(ID id)
: Deletes the entity with the given id.delete(T entity)
: Deletes a given entity.deleteAll(Iterable<? extends T> entities)
: Deletes all given entities.deleteAll()
: Deletes all entities.
These methods provide basic CRUD operations for entities, however, if you need more advanced queries you can define them in your repository interface and Spring will automatically implement them at runtime.
Thanks for Reading…