join more than one table in spring jparepository

2019-03-31 10:12发布

问题:

I am trying to fetch record by doing a join. I am new to spring jparepository. I understand that there is separate repository for each entity(table) where when i implement i need to define the entity and datatype of primary key.

Could anyone please suggest how can I fetch record by joining two tables.

I have two repo as below:

public interface AEntityRepository extends JpaRepository<AEntity, Integer>

public interface BEntityRepository extends JpaRepository<BEntity, Integer>

I want to join above two entity(AEntity, BEntity). I know I can have custom query using something like below:

@Query("SELECT ****** FROM AEntity ae")
AEntity findCustomrRecords();

However can I write the same kind of query (join query) with join. Do i need to have a separate repository implementing some other class.

Can anyone please help.

I am using mysql.

回答1:

I understand that there is separate repository for each entity(table)

This is a very common misunderstanding. You do not want to have a repository per entity, but per aggregate root. See http://static.olivergierke.de/lectures/ddd-and-spring/

Regarding your specific problem at hand: Creating a custom method in your repository interface and annotating it with a JPQL should do the trick. So you get something like:

@Query("select a from BEntity b join b.a a where b.foo = :foo")
AEntity getAllFooishAs(String foo);

You can use any join syntax JPQL offers in the query.