@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查询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);
我尝试了多种方法,但它给出了
org.hibernate.QueryException:非法尝试取消引用集合
最佳答案
正如我已经描述过的 Retrieve List from repository interface to DTO list您应该执行以下步骤:
- 首先使用您想要从查询输出返回的字段创建一个构造函数
- 在查询中,您应该创建 dto 的新实例并将字段从数据库传递到新安装:
所以你需要这些改变:
1。在构造函数中:
您不应将列表用作 List<String> models;
因为您应该将您的 dto 视为数据库的结果行。所以你需要有一个简单的 String model;
public CarModelDTO (String name,String model){
this.name=name;
this.model=model;
}
2。在@Query中:
- 您应该适本地使用多重内连接
您还应该将您的包名称附加到查询中的 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)
关于java - 使用集合加载 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52134820/