This post assumes that you are already familiar with Spring Data Repositories. Here, I’ll share a handy tip on using Spring Data.

For accessing data using Spring Data, we code repository interfaces, as below:

public interface UserRepository extends JpaRepository<User, Long> {
   ...
}

Notice the JpaRepository above. The first generic parameter there is the entity class name, and the second one is the type of primary key.

In most of the applications, we usually use the same primary key type throughout, which could be either Long or or maybe String. So, If you code your repositories as above, you’ll end up repeating the primary key generic parameter always.

You can avoid this repetition by coding a base repository as below:

@NoRepositoryBean
public abstract interface MyJpaRepository<T> extends JpaRepository<T, Long> {
   ...
}

If you have a base entity class from which all your entities extend, you can replace the first T above with T extends MyEntity, as below:

@NoRepositoryBean
public interface MyJpaRepository<T extends MyEntity> extends JpaRepository<T, Long> {
   ...
}

Then, you can have your repositories extend MyJpaRepository, as below:

public interface UserRepository extends MyJpaRepository<User> {
   ...
}

Hope it’d be handy!