@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;
}
在上述关系中,要返回CarModelDTO
JPA查询在哪里,
@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);
我尝试了多种方法,但是它给了
org.hibernate.QueryException: illegal attempt to dereference collection
答案 0 :(得分:1)
正如我已经描述过的Retrieve List from repository interface to DTO list,您应该执行以下步骤:
因此您需要进行以下更改:
您不应将列表用作List<String> models;
,因为您应该将dto视为DB的结果行。所以您需要一个简单的String model;
public CarModelDTO (String name,String model){
this.name=name;
this.model=model;
}
您还应该在查询中将包名称附加到CarModelDTO(在这里我使用com.example,您应该更改它)
@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)