查询oneToMany关系

时间:2018-08-13 14:58:34

标签: sql spring jpa spring-data-jpa

我正在寻找解决问题的方法。

我有这样的东西。

ZPN

除了关系B的img字段外,我想从数据库中获取所有记录。 也许可以在JPA中创建查询,但这如何解决?

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以将img定义为惰性:

@Basic(fetch=FetchType.LAZY)
@Lob
private byte[] img;

这样,仅当您访问吸气剂时才加载图像。

第二个选项是使用构造函数表达式创建DTO(数据传输对象):

package dto;

public class BDto {
   private final String name;
   private final A a;

   public BDto(String name, A a) {
       this.name = name;
       this.a = a;
   }

   // getters for both fields
}

然后您可以创建一个查询,例如:

select new dto.BDto(b.name, b.a) from B b where b.a.received = true

重要提示:dto必须在完全限定的查询中使用(例如dto.BDto)

答案 1 :(得分:0)

我创建了以下内容:

SELECT YearID, MonthID, SUM(Amount) FROM (

  SELECT YEAR(ORDREC.[Due Date]) as YearID, MONTH(ORDREC.[Due Date]) as MonthID, SUM(ORDREC.[Pay] * ORDREC.[Exchange Rate]) as Amount
  FROM orders-table AS ORDREC
  WHERE ...

UNION ALL

  SELECT YEAR(INV.[Date]) as YearID, MONTH(INV.[Date]) as MonthID, SUM(INV.[Subtotal] * INV.[Exchange Rate]) as Amount
  FROM invoices-table AS INV
  WHERE ...

) x GROUP BY YearID, MonthID

我遇到此错误:

 @Query(value = "select new pl.ddweb.dealer.web.rest.dto.ImageDTO(image.id, image.thumbnail, image.isMain, image.imgContentType, image.car) from Image image WHERE (image.car.received =:received) ORDER BY image.car.createdDate")
    Page<Car> findAllByReceivedOrderByCreatedDateDesc(@Param("received") Boolean received, Pageable pageable);