![](/img/trans.png)
[英]Postman showing empty JSON object from spring boot rest api
[英]Spring boot 3 Questions: Why it can't to call API with Postman and Frontend call API then get empty array?
我創建了一個 API,它被稱為搜索商店功能。 .
當我使用此 SQL 腳本在 MySql 中運行時。 它將顯示有效結果
SET @productName = null;
SET @BranchName = null;
SET @minPrice = 0;
SET @maxPrice = 10000;
SET @quantity = 1000;
SELECT * FROM stores s
INNER JOIN products p
ON p.id = s.product_id
INNER JOIN branches b
ON b.id = s.branch_id
WHERE (p.name LIKE CONCAT('%', @productName , '%') OR @productName IS NULL)
AND (b.name LIKE CONCAT('%', @branchName , '%') OR @branchName IS NULL)
AND (@minPrice <= p.price AND p.price <= @maxPrice)
AND s.quantity <= @quantity
ORDER BY p.name, b.name, quantity;
.
當我通過前端調用它時, StoreService.java 中的日志是...
productName: null, minPrice: 0.0, maxPrice: 15000.0, branchName: null, 1000
Hibernate: SELECT * FROM stores s INNER JOIN products p ON p.id = s.product_id INNER JOIN branches b ON b.id = s.branch_id WHERE (p.name LIKE CONCAT('%', ? , '%') OR ? IS NULL) AND (b.name LIKE CONCAT('%', ? , '%') OR ? IS NULL) AND (? <= p.price AND p.price <= ?) AND s.quantity <= ? ORDER BY p.name
Stores: []
.
郵遞員參數圖像
當郵遞員調用它時會得到
java.lang.StackOverflowError: null
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:944) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.19.jar:8.0.19]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.2.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.2.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:390) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:163) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:104) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:707) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:76) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2145) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:589) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:264) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:458) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at com.g_able.back_g_exam.entity.Product.hashCode(Product.java:12) ~[classes/:na]
at com.g_able.back_g_exam.entity.Store.hashCode(Store.java:13) ~[classes/:na]
at java.util.HashMap.hash(HashMap.java:339) ~[na:1.8.0_172]
at java.util.HashMap.put(HashMap.java:612) ~[na:1.8.0_172]
at java.util.HashSet.add(HashSet.java:220) ~[na:1.8.0_172]
at java.util.AbstractCollection.addAll(AbstractCollection.java:344) ~[na:1.8.0_172]
at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:355) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:239) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:224) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:198) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:154) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:267) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:218) ~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
.
@GetMapping("/api/v1/stores/advance-search")
public List<Store> findStoresByFilter(
@RequestParam(required = false) String productName, @RequestParam(required = false) String branchName,
@RequestParam(required = false, defaultValue = "0") Integer minPrice,
@RequestParam(required = false, defaultValue = "999999") Integer maxPrice,
@RequestParam(required = false, defaultValue = "3000") Integer quantity) {
ProductParams productParams = ProductParams.builder().name(productName).minPrice(minPrice).maxPrice(maxPrice).build();
Branch branch = Branch.builder().name(branchName).build();
List<Store> stores = storeService.findStoresByFilter(productParams, branch, quantity);
System.out.println("Stores: " + stores);
return stores;
}
.
public List<Store> findStoresByFilter(ProductParams productParams, Branch branch, int quantity) {
System.out.println("productName: " + productParams.getName() + ", minPrice: " + productParams.getMinPrice() + ", maxPrice: "
+ productParams.getMaxPrice() + ", branchName: " + branch.getName() + ", " + quantity);
return storeRepository.searchStoresByFilter(productParams.getName(), branch.getName(),
productParams.getMinPrice(), productParams.getMaxPrice(), quantity);
}
.
@Query(nativeQuery = true,
value = "SELECT * " +
"FROM stores s " +
"INNER JOIN products p " +
"ON p.id = s.product_id " +
"INNER JOIN branches b " +
"ON b.id = s.branch_id " +
"WHERE (p.name LIKE CONCAT('%', :productName , '%') OR :productName IS NULL) " +
" AND (b.name LIKE CONCAT('%', :branchName , '%') OR :branchName IS NULL) " +
" AND (:minPrice <= p.price AND p.price <= :maxPrice) " +
" AND s.quantity <= :quantity " +
" ORDER BY p.name")
List<Store> searchStoresByFilter(@Param("productName") String productName, @Param("branchName") String branchName,
@Param("minPrice") double minPrice, @Param("maxPrice") double maxPrice, @Param("quantity") int quantity);
我在我的POJO 類中被標記,他們對javax.persistence包中的@Table和@JoinColumn發出警告
Cannot resolve table 'table_name'
@Table 中的Cannot resolve table 'table_name'
並且Cannot resolve column 'product_id'
Cannot resolve column 'branch_id'
在@JoinColumn
非常感謝您的幫助
我在我的實體類中被標記,他們有來自 javax.persistence 的關於 @Table 的警告無法解析 @Table 中的表 'table_name' 並且無法解析列 'product_id' 無法解析 @JoinColumn 中的列 'branch_id'
這就是 hibernate 不能真正映射表的原因,你需要先修復映射,所以 hibernate 知道要使用哪個表。 目前它在 sql 中尋找“table_name”,這不是您的商店或產品表。 我們不知道您的映射是否正確,因為您的實體類代碼未在此處共享,但注釋或 xml 文件可能具有錯誤本身的錯誤映射名稱,最終導致整個請求崩潰。
編輯:請檢查這些庫是否包含在您的類路徑中:hibernate-annotations.jar lib/hibernate-comons-annotations.jar lib/ejb3-persistence.jar
此外,我建議您使用休眠查詢語言而不是本機查詢,因為當您想要切換基礎數據庫時,它們的可擴展性要高得多。
根本原因是,hibernate 是數據庫抽象層又名 DBAL,該庫的全部目的是代表您的代碼構建查詢並執行它們。 您正在嘗試將其用作本機 sql 包裝器,並且 sql 查詢會將結果提供給 hibernate,但由於映射錯誤,因此無法在實體中解析和存儲數據,雖然它在某些情況下很有用,但 hibernate 本身提供了更強大的功能,例如延遲加載、實體關系等等。
您可以在此處閱讀完整文檔以使用此類功能。 入門指南
我已經找到了如何修復 Postman 無法完成此 API 並且前端獲得空數組的方法。
我只是將@ToString(exclude = "stores")
和@EqualsAndHashCode(exclude = "stores")
到具有多對多關聯的實體中。
實體中的當前代碼是:
@Data
@ToString(exclude = "stores")
@EqualsAndHashCode(exclude = "stores")
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "products")
@Builder(toBuilder = true)
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false, length = 50)
private String name;
private String detail;
private double price;
@JsonIgnore
@OneToMany(mappedBy = "product")
private Set<Store> stores;
}
@Data
@ToString(exclude = "stores")
@EqualsAndHashCode(exclude = "stores")
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "branches")
@Builder(toBuilder = true)
public class Branch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false, length = 60)
private String name;
@JsonIgnore
@OneToMany(mappedBy = "branch")
private Set<Store> stores;
}
但我不明白為什么它會出錯。 你能解釋一下嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.