springboot~@Query到(dao)DTO對象
我們有時(shi)在進行開發過程中,使用jpa的@Query注解(jie)去選擇多張表然后返(fan)回一(yi)(yi)個DTO對象(xiang),這個時(shi)候我們需(xu)要特殊處(chu)理(li)一(yi)(yi)下,因(yin)為默認(ren)(ren)情(qing)況下,你的jpa代碼是(shi)不認(ren)(ren)DTO對象(xiang)的。
參考文章:
- entity實體
@Entity
@Getter
@Setter
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class OrderInfo extends EntityBase {
@Id
@GeneratedValue
private int id;
private int userId;
private String userName;
private double total;
private String shippingName;
private String shippingAddress;
private Date orderTime;
}
@Entity
@Getter
@Setter
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class OrderItem extends EntityBase {
@Id
@GeneratedValue
private int id;
private int orderId;
private int productId;
private String productName;
private int count;
private double salePrice;
}
/**
* DTO對象
*/
@Getter
@Setter
@Builder
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class OrderList {
public int id;
private int userId;
private String userName;
private int productId;
private String productName;
private int count;
private double salePrice;
}
- repository方法
@Query("select new com.lind.microservice.productCenter.dto.OrderList" +
"( o.id,o.userId,o.userName,oi.productId,oi.productName,oi.count,oi.salePrice) " +
" from OrderInfo o " +
" join OrderItem oi on o.id=oi.orderId")
List<OrderList> getOrderInfos();
- 結果
[
{
"id": 5,
"userId": 3,
"userName": "lind",
"productId": 4,
"productName": "足球",
"count": 1,
"salePrice": 99
}
]