[email protected]到DTO物件
阿新 • • 發佈:2018-12-29
我們有時在進行開發過程中,使用jpa的@Query註解去選擇多張表然後返回一個DTO物件,這個時候我們需要特殊處理一下,因為預設情況下,你的jpa程式碼是不認DTO物件的。
參考文章:https://smarterco.de/spring-data-jpa-query-result-to-dto/
- 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
}
]