Selecting from Multiple Tables in Spring Data

前端 未结 1 639
青春惊慌失措
青春惊慌失措 2020-12-15 14:40

I need to write a select query fetching data from multiple tables in Spring Data Repository layer. I know we can use @Query to write custom queries, but that returns value f

1条回答
  •  时光说笑
    2020-12-15 15:05

    Your Interface method can use native SQL to select columns from multiple tables and the method will return a list of object arrays :

    public interface MyRepository extends JpaRepository {
      @Query(name = [name], nativeQuery = true)
      List methodThatQueriesMultipleTables();
    }
    

    Each item in the list is Object array that is a row of data

    You can also create a Custom Repository Implementation :

    How to add custom method to Spring Data JPA

    @NoRepositoryBean
    public interface CustomRepository<[Your object]> {
        List methodThatQueriesMultipleTables();
    }
    
    public class MyRepositoryImpl<[Your object]> implements CustomRepository<[Your object] {
        @PersistenceContext
        private EntityManager entityManager;
    
        @Override
        public List methodThatQueriesMultipleTables() {
            //use JPA query to select columns from different tables
            Query nativeQuery = entityManager.createNativeQuery("query");
            return query.getResultList();
        }
    }
    

    0 讨论(0)
提交回复
热议问题