Databases Reference
In-Depth Information
Let's call this interface
BaseRepository
. Its source code is given as follows:
@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends
JpaRepository<T, ID>, QueryDslPredicateExecutor<T> {
public T deleteById(ID id) throws NotFoundException;
}
Implementing the base repository interface
Next we have to write an implementation of the
BaseRepository<T, ID>
interface.
This process includes the following steps:
1.
Create a class that implements the
BaseRepository<T, ID>
interface and
extends the
QueryDslJpaRepository<T, ID>
class. This ensures that the
class has access to the methods provided by the
JpaRepository<T, ID>
interface and that Querydsl can be used.
2.
Add a constructor that is used to simply pass the needed information
forward to the superclass.
3.
Implement the
deleteById()
method. First, this method obtains the deleted
entity. If an entity is not found, this method throws
NotFoundException
.
Otherwise this method deletes the found entity and returns the deleted entity.
The source code of the created
GenericBaseRepository
class is given as follows:
public class GenericBaseRepository<T, ID extends Serializable> extends
QueryDslJpaRepository<T, ID> implements BaseRepository<T, ID> {
public GenericBaseRepository(JpaEntityInformation<T, ID>
entityMetadata, EntityManager entityManager) {
super(entityMetadata, entityManager);
}
@Override
public T deleteById(ID id) throws NotFoundException {
T deleted = findOne(id);
if (deleted == null) {
throw new NotFoundException();