convert or cast output of JpaRepository

convert or cast output of JpaRepository

Problem Description:

I have three interfaces that extend JpaRepository and a custom interface that has two functions. These two functions have their special output in each of three interfaces.
I implement it with List in the custom interface, so I have to use same output in the three interfaces, but I need to convert them to their special type.
Here is the custom interface:

public interface DataRepo {

  List<Object> findAllEmptyData();
  List<Object> findAllByCreatedAtBefore(String createdAt);
}

And here are the three interfaces:

public interface bTableRepo extends JpaRepository<bTable, Integer>, DataRepo {

  @Query("SELECT b FROM bTable b WHERE b.value is null AND b.data")
  List<Object> findAllEmptyData();

  @Query("SELECT b FROM bTable b WHERE b.createdAt < ?1")
  List<Object> findAllByCreatedAtBefore(LocalDate createdAt); //I need to convert List<Object> to List<bTable>
}

public interface cTableRepo extends JpaRepository<cTable, Integer>, DataRepo {

  @Query("SELECT c FROM cTable c WHERE c.value is null AND c.dData is null AND c.date is null")
  List<Object> findAllEmptyData();

  @Query("SELECT c FROM cTable c WHERE c.createdAt < ?1")
  List<Object> findAllByCreatedAtBefore(LocalDate createdAt); //I need to convert List<Object> to List<cTable>
}

public interface dTableRepo extends JpaRepository<dTable, Integer>, DataRepo {

  @Query("SELECT d FROM dTable d WHERE d.value is null AND d.date is null AND d.DateAndTime is null")
  List<Object> findAllEmptyData();

  @Query("SELECT d FROM cTable d WHERE d.createdAt < ?1")
  List<Object> findAllByCreatedAtBefore(LocalDate createdAt); //I need to convert List<Object> to List<dTable>
}

Solution – 1

Make your custom repo generic:

public interface DataRepo<T> {

  List<T> findAllEmptyData();
  List<T> findAllByCreatedAtBefore(String createdAt);
}

And then use it for example with bTable:

public interface bTableRepo extends JpaRepository<bTable, Integer>, DataRepo<bTable> {
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject