0

I have @Entity, which looks like this

@Entity
public class Plane {

  @Id
  private Long planeid;

  @OneToMany(fetch = FetchType.LAZY, targetEntity = Passenger.class, cascade ={CascadeType.ALL}, mappedBy = "planeid")
  private List<Passenger> passengers;

...

I am using such method in interface extending JPARepository:

@Transactional
public interface PlaneRepository extends JpaRepository<Plane, Long> {

    @Query(value = "SELECT * FROM planes p JOIN passengers v USING(planeid) WHERE v.name = 'Carlos' GROUP BY p.planeid", nativeQuery = true)
    List<Plane> findAllPlanesMatching();

}

As a result of this method I get list of all plane objects, which have passenger with name 'Carlos', but inside of every plane object List contains list of all passenger, but I would like this list have only passengers called 'Carlos'. Is there any way to do that?

1 Answers1

0

You are mixing two modes: entity mapping and native query mapping. Native query you use does not work directly with entity mapping. Look at this discussion: JPA : How to convert a native query result set to POJO class collection

In your case, I don't see why you can't use JPA all way through with JPQL queries.

You need to map a @ManyToOne relationship in the Passenger class

@ManyToOne
private Plane plane;

and run this query:

Query q = em.createQuery("FROM Passenger p WHERE p.name = :name")
            .setParameter("name", "Carlos")
            .getResultList();

You will get only passenger matching the name Carlos, and you can access their planes traversing p.getPlane().

Community
  • 1
  • 1
nolexa
  • 2,392
  • 2
  • 19
  • 19