Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using QueryDslRepositorySupport in combination with interface repositories

since I didn't get a reply on the spring forum I'll give it a try here.

Is there a way to have a common interface repository which is extended by interfaces the following way:

@NoRepositoryBean
public interface CommonRepository<T> extends JpaRepository<T, Long>, QueryDslPredicateExecutor<T> {
 T getById(final long id);
}

@Repository
public interface ConcreteRepository extends CommonRepository<ConcreteEntity> {
  List<ConcreteEntity> getByNameAndAddress(final String name, final String address);
}

public class ConcreteRepositoryImpl extends QueryDslRepositorySupport implements ConcreteRepository {

    private BooleanExpression nameEquals(final QConcreteEntity entity, final String name) {
        return entity.eq(name);
    }

    public List<ConcreteEntity> getByNameAndAddress(final String name, final String address) {
        QConcreteEntity entity = QConcreteEntity.concreteEntity;
        return from(entity).where(entity.name.eq(name).and(entity.address.eq(address))).list(entity);
    }
}

The problem with the implementation is that I have to implement getById(final long id) in each concrete class. I don't want to do that. Normally, spring data automatically knows about each entity. Also I want to have the functionality of QueryDslRepositorySupport. In my example it normally generates something like:

select .. from concreteentity en where en.id = ...

Is there a way to solve it? I already stumbled upon Spring Jpa adding custom functionality to all repositories and at the same time other custom funcs to a single repository

and

http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations

but I don't think these solutions are helpful and I don't entirely understand how I can use them to solve the problem.

Thanks,

Christian

like image 248
christian meyer Avatar asked Nov 10 '22 14:11

christian meyer


1 Answers

One way to create a generic getById under QuerydslRepositorySupport is like this

T getById(long id) {
    return getEntityManager().find(getBuilder().getType(), id)
}
like image 165
Timo Westkämper Avatar answered Nov 15 '22 12:11

Timo Westkämper