Я разрабатываю api Spring Boot rest.У меня есть два следующих объекта Hibernate:
OrderEntity
@Table(name = "orders")
@Getter
@Setter
public @Entity class OrderEntity extends AbstractPersistable<Long> {
private static final long serialVersionUID = 1780337491454957180L;
@Column(name = "order_number")
@Setter(value = AccessLevel.NONE)
private String orderId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private UserEntity user;
@Digits(integer = 10, fraction = 2)
@Column(name = "total_amount")
@Range(min = 0, message = "The total amount must be greater or equals to zero.")
private BigDecimal totalAmount = BigDecimal.ZERO;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<OrderDetailEntity> items = new HashSet<>();
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(nullable = false, name = "card_details_id")
private CardDetailsEntity card;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(nullable = false, name = "shipping_address_id")
private AddressEntity shippingAddress;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(nullable = true, name = "billing_address_id")
private AddressEntity billingAddress;
@Column(name = "one_address", columnDefinition = "BOOLEAN")
private boolean oneAddress;
public void addOrderDetail(OrderDetailEntity detail) {
items.add(detail);
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(orderId).append(" (").append(totalAmount).append(") ");
items.forEach(i -> buffer.append(i.getProduct().getName()).append("; qty: ").append(i.getQuantity())
.append("; amount: ").append(i.getTotalAmount()).append(System.lineSeparator()));
return buffer.append("]").toString();
}
public void setOrderId(UUID uuid) {
orderId = uuid.toString();
}
}
и:
OrderDetailEntity
@Table(name = "order_detail")
@Getter @Setter
@NoArgsConstructor(access = AccessLevel.PUBLIC)
public @Entity class OrderDetailEntity extends AbstractPersistable<Long> {
private static final long serialVersionUID = 8128749778263610480L;
@Column(name = "quantity")
private Integer quantity;
@Digits(integer = 10, fraction = 2)
@Column(name = "total_amount")
@Range(min = 0, message = "The total amount must be greater or equals to zero.")
private BigDecimal totalAmount = BigDecimal.ZERO;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id")
@JsonBackReference
private OrderEntity order;
@OneToOne(optional = false)
@JoinColumn(name = "product_id")
private ProductEntity product;
}
Также я написал пружинный репозиторий jpa для заказов и деталей заказа:
@Repository
public interface OrderRepository extends JpaRepository<OrderEntity, Long> {
@Query("SELECT o FROM OrderEntity o LEFT JOIN FETCH o.items i WHERE o.user.email = ?1")
List<OrderEntity> findOrdersByUser(String email);
}
@Repository
public interface OrderDetailRepository extends JpaRepository<OrderDetailEntity, Long> {
@Query("SELECT d FROM OrderDetailEntity d LEFT JOIN FETCH d.order o WHERE o.orderId = ?1")
List<OrderDetailEntity> findOrderItemsByUser(String orderId);
}
услуг :
@Transactional(readOnly = true)
public List<OrderDetailEntity> getOrderItems(final long userId, final String orderId) {
String currentUser = SecurityUtil.getCurrentUserEmail();
List<OrderDetailEntity> orderDetails = userService.findOneByEmail(currentUser)
.filter(user -> user.getId() == userId)
.map(user -> {
return orderDetailRepository.findOrderItemsByUser(orderId);
}).orElseThrow(() -> new RuntimeException());
return orderDetails;
}
@Transactional(readOnly = true)
public List<OrderEntity> getOrders(final long userId) {
String currentUser = SecurityUtil.getCurrentUserEmail();
List<OrderEntity> orders = userService.findOneByEmail(currentUser)
.filter(user -> user.getId() == userId)
.map(user -> {
return orderRepository.findOrdersByUser(user.getEmail());
}).orElseThrow(() -> new RuntimeException());
return orders;
}
И методы контроллера (конечные точки):
@GetMapping("/users/{userId}/orders")
public List<OrderEntity> getOrders(@PathVariable Long userId) {
return orderService.getOrders(userId);
}
@GetMapping("/users/{userId}/orders/{orderId}")
public List<OrderDetailEntity> getOrderItems(@PathVariable Long userId, @PathVariable String orderId) {
return orderService.getOrderItems(userId, orderId);
}
В обоих ответах некоторые ассоциации не включены. Лучший пример:
ЕслиЯ выполняю следующий запрос:
curl -X GET "http://localhost:8080/users/1/orders/d329cba4-5ead-4f5d-9663-557e99ab46f1"
Я получил следующий результат:
[ {
"quantity" : 1,
"totalAmount" : 105.00,
"new" : false
} ]
, который не содержит ссылку product
, а только количество полей и totalAmount
.
Кроме того, если я запускаю следующий запрос:
curl -X GET "http://localhost:8080/users/1/orders"
[ {
"created" : "2018-05-12T14:02:00",
"orderId" : "d329cba4-5ead-4f5d-9663-557e99ab46f1",
"totalAmount" : 105.00,
"card" : {
"created" : "2018-05-12T14:02:00",
"brand" : "American Express",
"expMonth" : 2,
"expYear" : 2022,
"last4" : "0005",
"new" : false,
"links" : [ ],
"content" : [ ],
"links" : [ ]
},
"shippingAddress" : {
"modified" : "2018-05-12T14:02:00",
"created" : "2018-05-12T14:02:00",
"streetAddress" : "test",
"country" : "Netherlands",
"city" : "test",
"state" : "test",
"postalCode" : "test",
"new" : false,
"links" : [ ],
"content" : [ ],
"links" : [ ]
},
"billingAddress" : {
"modified" : "2018-05-12T14:02:00",
"created" : "2018-05-12T14:02:00",
"streetAddress" : "test",
"country" : "Netherlands",
"city" : "test",
"state" : "test",
"postalCode" : "test",
"new" : false,
"links" : [ ],
"content" : [ ],
"links" : [ ]
},
"oneAddress" : true,
"new" : false
} ]
Этот ответ не содержит поле items
, которое мне также нужно получить из ответа, даже если с ним связаны элементыс любым заказом.В чем проблема?Почему вышеприведенные поля не включены в ответ?
Спасибо
РЕДАКТИРОВАТЬ
Я пытался добавить в OrderDetailEntity
следующее поле:
@OneToOne
@JoinColumn(name = "address_id")
private AddressEntity address;
Это затем правильно сериализовано:
curl -X GET "http://localhost:8080/users/1/orders/2f8254e6-b04a-4fb0-baae-cb27fcd11a87"
[ {
"quantity" : 1,
"totalAmount" : 10.99,
"address" : {
"streetAddress" : "aa",
"country" : "Netherlands",
"city" : "aa",
"state" : "a",
"postalCode" : "a",
"modified" : "2018-05-12T18:49:48",
"created" : "2018-05-12T18:49:48",
"new" : false,
"links" : [ ],
"content" : [ ],
"links" : [ ]
},
"id" : 8,
"new" : false
Но ProductEntity не сериализуется.Ниже приведены две сущности.Я не могу понять разницу.Может быть, ProductEntity содержит другие ассоциации (а AddressEntity нет), которые могут как-то повлиять на сериализацию?
ProductEntity
@Table(name = "product")
@Getter @Setter
@NoArgsConstructor(access = AccessLevel.PUBLIC) @AllArgsConstructor
public @Entity class ProductEntity extends AbstractPersistable<Long> {
private static final long serialVersionUID = -5077959382034660336L;
@NotEmpty
@Column(name = "product_name", length = 254)
private String name;
@NotEmpty
@Column(name = "product_description", length = 254)
private String description;
@Digits(integer = 12, fraction = 2)
@Column(name = "product_price")
@Range(min = 0, message = "The price must be greater or equals to 0.")
private BigDecimal price;
@NotEmpty
@Column(name = "image_url", length = 254)
private String imageUrl;
@ManyToOne(optional = false, fetch = FetchType.EAGER)
@JoinColumn(name = "product_category_id")
@JsonBackReference
@JsonIgnore
private CategoryEntity category;
@OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@BatchSize(size = 10)
@OrderBy
private SortedSet<ProductThumbnailEntity> thumbnails;
public ProductEntity(Long id) {
this.setId(id);
}
public ProductEntity(String name, String description, BigDecimal price) {
this.name = name;
this.description = description;
this.price = price;
}
}
AddressEntity
@Table(name = "address")
@Getter @Setter
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
public @Entity class AddressEntity extends AbstractEntity<Long> {
private static final long serialVersionUID = 1544232699919709073L;
@Size(max = 254)@Column(name = "street_address")
private String streetAddress;
@Size(max = 50)
private String country;
@Size(max = 40)
private String city;
@Size(max = 100)
private String state;
@Size(max = 16) @Column(name = "postal_code")
private String postalCode;
}