2
我有以下關係:避免加載延遲集合在Spring數據JPA
@Entity class Shop {
@OneToMany(mappedBy = "shop", fetch = LAZY)
private List<Employee> employees = new LinkedList<>();
}
和
@Entity class Employee {
@ManyToOne
private Shop shop;
}
我已經聲明春天數據存儲庫這樣的:
public interface ShopRepository extends JpaRepository<Shop, Long> {}
調用ShopRepository#findOne(id)
方法強制取回List<Employee> employees
這是LAZY
的關係。
我有一個使用店鋪倉庫服務:
@Service
@Transactional(readOnly = true)
public class ShopService {
private final ShopRepository shopRepository;
@Autowired
public ShopService(ShopRepository shopRepository) {
this.shopRepository = shopRepository;
}
public Shop find(Long id) {
return shopRepository.findOne(id);
}
} 服務方法被調用另一個控制器方法中:
@RequestMapping(value = "api/schedule/{shopId:[0-9]+}/{date:\\d{4}-\\d{2}-\\d{2}}", method = RequestMethod.GET)
@ResponseBody
public Schedule getSchedule(@PathVariable Long shopId,
@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
Schedule schedule = scheduleService.findSchedule(shopId, date);
if(schedule != null)
return schedule;
else {
Shop shop = shopService.find(shopId);
Schedule empty = new Schedule(shop, date);
return empty;
}
}
如何擺脫獲取employees
的關係呢?
我看不出這將是除非東西在你的代碼被明確觸發負荷的情況下。顯示調用回購的方法中的所有代碼。 –
@alanhay,我添加了調用回購方法的代碼。 – mrom
你在使用Spring Data Rest嗎?你的控制器是一個'@ RepositoryRestController'嗎?如果是這樣的話:http://stackoverflow.com/questions/30910996/spring-jpa-repository-ignoring-fetchtype-lazy –