仅从JPA查询中获取选定的数据

时间:2017-03-08 23:05:49

标签: jpa repository spring-data spring-data-jpa

我找不到任何可以从域中获取所选数据的好解决方案? E.g我上课了:

@Entity
public class Reservation {

// private Integer RESERVATION_ID;
// private Integer id;
private long code;
private Date date;
private Client reservationClient;
private WashType reservationWashType;
private Vehicle reservationVehicle;
private Wash reservationWash;
private Worker reservationWorkerPesel;
private Review reservationReview;
private ReservationReminder reservationReminder;
 }

拥有简单的查询存储库

public interface ReservationRepository extends JpaRepository<Reservation, Long> {
Reservation findByCode(long code);
}

我想从该查询中获取Reservation对象,但没有来自Review,Worker等类的数据。 所以这意味着我的结果应该是这样的: 整个预订对象,包括: 代码,日期,客户预订客户,WashType reservationWashType,车辆预订车辆,洗车预订洗车,预订提醒预订提醒

是否有可能以良好的方式排除它?或者如果不能,我该如何管理呢?

1 个答案:

答案 0 :(得分:0)

是的,只要public class SampleActivityTests extends ActivityInstrumentationTestCase2<SampleActivity> { private UiDevice mDevice; public SampleActivityTests() { super(SampleActivity.class); } @Override public void setUp() throws Exception { super.setUp(); getActivity(); mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); } public void testAddNote() throws InterruptedException { // Take a screenshot when app becomes visible. onView(isRoot()); ScreenShotter.takeScreenshot("sample 1", getActivity()); mDevice.pressDPadLeft(); mDevice.pressDPadLeft(); ScreenShotter.takeScreenshot("sample 2", getActivity()); } } Review被标记为延迟加载,您就可以轻松完成此操作。

我的意思是:

Worker

在您致电@ManyToOne(fetch = FetchType.LAZY) private Review review; 之前,Hibernate不会尝试加载Review关联。

对于您希望#getReview()使用Reservation的情况,您只需要在查询时指定您希望加入关联的关系。

Review

请记住,如果@Query("SELECT r FROM Reservation r JOIN FETCH r.review WHERE r.code = :code") List<Reservation> findByCode(Long code); 不能为null,请确保Review具有@ManyToOne属性,以便在生成联接时,它使用内部联接而不是外部联接避免性能开销。