避免在Spring数据Jpa中加载惰性集合
我有以下关系:避免在Spring数据Jpa中加载惰性集合,jpa,spring-data-jpa,Jpa,Spring Data Jpa,我有以下关系: @Entity class Shop { @OneToMany(mappedBy = "shop", fetch = LAZY) private List<Employee> employees = new LinkedList<>(); } 我这样声明了Spring数据存储库: public interface ShopRepository extends JpaRepository<Shop, Long> {} } 服务方法在另一个控制
@Entity class Shop {
@OneToMany(mappedBy = "shop", fetch = LAZY)
private List<Employee> employees = new LinkedList<>();
}
我这样声明了Spring数据存储库:
public interface ShopRepository extends JpaRepository<Shop, Long> {}
}
服务方法在另一个控制器方法中调用:
@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;
}
}
如何摆脱抓取员工的关系?
我找到了解决方案
实际上,我在实体上使用了@JsonManagedReference/@jsonbackreference来防止在封送到JSON时循环。这会导致获取延迟加载数据。
为了避免这种情况,您应该将Hibernate4Module
添加到MappingJackson2HttpMessageConverter
更多信息请参见本文:除非代码中有明确触发加载的内容,否则我看不出情况会如何。显示调用repo的方法中的所有代码。@alanhay,我已经添加了调用repo的方法所涉及的代码。您使用的是Spring数据Rest吗。您的控制器是
@RepositoryRestController
?如果是:@alan,谢谢你的帮助。你的链接很有帮助。
@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;
}
}