[英]How can I get List of nested objects using JpaRepository?
我無法使用JpaRepository
獲取嵌套對象的列表。 我將嘗試使用以下代碼解釋我想要的內容:
AutoService實體:
@Entity
public class AutoService {
@Id
private long id;
@Column(name = "serviceName", nullable = false)
private String serviceName;
}
服務實體:
@Entity
public class Service {
@Id
private long serviceId;
@Column(name = "serviceName", nullable = false)
private String serviceName;
@Column(name = "category", nullable = false)
private String category;
@ManyToOne
@JoinColumn(name = "autoServiceId", nullable = false)
private AutoService autoService;
}
ServiceRepository接口:
public interface ServiceRepository extends JpaRepository<Service, Long> {
List<Service> findByServiceNameAndCategory(String autoServiceName, String categoryName);
}
商業邏輯:
@org.springframework.stereotype.Service
public class ServiceServiceImpl implements ServiceService {
@Autowired
private ServiceRepository serviceRepository;
@Override
public List<Service> findByAutoServiceAndCategory(String autoServiceName, String serviceCategory) {
return serviceRepository.findByServiceNameAndCategory(autoServiceName, serviceCategory);
}
}
如我所料,上面的代碼無法提供與提供的類別和AutoService
名稱匹配的Service
的所需列表。
有人可以通過以下方式提供有關如何使用我的存儲庫獲取autoServiceName
服務列表的autoServiceName
嗎: autoServiceName
和serviceCategory
?
編輯 :
現在,我正在使用自定義查詢。
我現在使用的是autoServiceId而不是服務名稱。
但是由於某種原因,我得到的對象列表為空。
這是我的JPA回購。
public interface ServiceRepository extends JpaRepository<Service, Long> {
@Query("SELECT s from Service s where s.autoService.id = :autoServiceId and s.category = :categoryName")
List<Service> findByServiceNameAndCategory(@Param("autoServiceId") Long autoServiceId, @Param("categoryName") String categoryName);
}
有什么建議嗎?
您可能必須在ServiceRepository
編寫這樣的查詢。
public interface ServiceRepository extends JpaRepository<Service, Long> {
@Query("SELECT s from Service s where s.autoService.serviceName = :autoServiceName and s.category = :categoryName")
Set<Round> getRoundsBySessionQuestionId(@Param("autoServiceName") String autoServiceName, @Param("categoryName") String categoryName);
}
希望這可以幫助。 編碼愉快!
由於您在AutoService
和Service
實體中均具有serviceName
屬性,因此ServiceRepository.findByServiceNameAndCategory
等效於以下SQL查詢:
SELECT
*
FROM
Service
WHERE
serviceName = ?
AND category = ?
可以看出,該查詢根本沒有命中AutoService
實體,這就是為什么結果不符合預期的原因。
正確的存儲庫方法是:
public interface ServiceRepository extends JpaRepository<Service, Long> {
List<Service> findByCategoryAndAutoServiceServiceName(String category, String autoServiceName);
}
此方法將按預期方式通過其serviceName
搜索嵌套的AutoService
對象。
Github上提供了一個示例項目 ,以演示此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.