Announcement Announcement Module
Collapse
No announcement yet.
Ho to use JpaRepository for fetching data from multiple tables Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Ho to use JpaRepository for fetching data from multiple tables

    Hello,
    I am leraning Spring JPA capabilities and looking on the JpaRepository. I know we can reduce lots of code by using JpaRepository. But, my concern here is that, how can we use JpaRepository when we want to fetch data from more than one tables. If we use EntityManager we can write a JPA Query and retrieve the data as List of Object array.

    How can we solve this kind of issues using JpaRepository?

    Could someone help by providing a best solution for this scenario please?

    Thanks
    Francis

  • #2
    Well scenario one you have an Entity that has multiple source tables in which case it is a JPA mapping issue and you use @SecondaryTables.

    Scenario 2 is you just want to write some custom queries. For this I would recommend you take a look at spring blog and the spring-data-jpa reference documentation. But it would look something like this:

    Code:
    public interface CustomerRepository extends JpaRepository<Customer, Long>, CustomerRepositoryCustom{
    
        @Query(""Select ..."")
        List<Customer> findxxx(@Param("myparam") String param);
    }
    
    public interface CustomerRepositoryCustom{
          Object[] mycustomQuery();
    }
    
    
    public class CustomerRepositoryImpl implements CustomerRepositoryCustom{
    	@PersistenceContext
    	EntityManager entityManager;
    
    	@Override
    	Object[] myCustomQuery(){
    		...your custom implementation here
    	}   
    }
    
    //Then you would use it as follows:
    
    public class SomeClass{
    	@Autowired
    	CustomerRepository customerRepository;
    	
    	public void somemethod(){
    		String param = "foo";
    		Object[] objectArray = customerRepository.myCustomQuery();
    		List<Customer> customerlist = customerRepository.findxxx(param);
    	}
    
    }
    Last edited by wgorder; Feb 14th, 2012, 09:22 AM.

    Comment

    Working...
    X