Aditya_G
Aditya_G

Reputation: 41

Loading DTO with collection

@Entity
@Table(name = "person")
public class Consignment implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "person_id")
    private String personId;

    @Column(name = "person_name")
    private String personName;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "person")
    @Column(name = "cars_owned")
    private Set<Cars> casrsowned = new HashSet<>();
}
@Entity
@Table(name = "cars")
public class Cars implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

   @Column(name = "cars_id")
    private String carsId; 


  @ManyToOne
    @JoinColumn(name = "person")
    private Person person;

    @OneToOne
    private CarsDetail  carsDetail;
}
@Entity
@Table(name = "carsDetail")
public class CarsDetail implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "brand")
    private String brand;

    @Column(name = "color")
    private String color;

    @Column(name = "model")
    private String model;
}
class CarModelDTO {

    String personName;
    List<String> models;
}

In the above relation, want to return CarModelDTO JPA query where,

@Query("Select CarModelDTO(p.personName, p.casrsowned.carsDetail.model) from Person as p where p`enter code here`.id = :id"))
public CarModelDTO getCarmodelOwnedByAperson(@Param("id") Long id);

I tried multiple ways but it gives org.hibernate.QueryException: illegal attempt to dereference collection

Upvotes: 1

Views: 1357

Answers (1)

Mohammadreza  Alagheband
Mohammadreza Alagheband

Reputation: 2230

As I have already described Retrieve List from repository interface to DTO list you should go through the following step :

  1. first create a constructor using the fields you want to be returned from the query output
  2. in you query you should create new instance of your dto and pass the field from db to new instalnce :

so you need these changes:

1. In the constructor:

You should not use a list as List<String> models; as you should consider that your dto as a result row of DB. so you need to have a simple String model;

    public CarModelDTO (String name,String model){    
        this.name=name;
        this.model=model;   
    }

2. In the @Query:

  • you should use multi inner join appropriately
  • you should also append your package name to CarModelDTO in the query (here i used com.example you should change it)

        @Query("Select com.example.CarModelDTO(p.personName, d.model ) from Person as p inner join p.carsowned c inner join c.carDetail d where p`enter code here`.id = :id")) 
        public CarModelDTO getCarmodelOwnedByAperson(@Param("id") Long id)
    

Upvotes: 1

Related Questions