Reputation: 41
@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
Reputation: 2230
As I have already described Retrieve List from repository interface to DTO list you should go through the following step :
so you need these changes:
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;
}
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