避免在Spring Data Jpa中加载LAZY集合

时间:2016-05-13 09:00:00

标签: jpa spring-data-jpa

我有以下关系:

@Entity class Shop {
@OneToMany(mappedBy = "shop", fetch = LAZY)
private List<Employee> employees = new LinkedList<>();
}

@Entity class Employee {
@ManyToOne
private Shop shop;
}

我已经像这样声明了Spring Data存储库:

public interface ShopRepository extends JpaRepository<Shop, Long> {}

调用ShopRepository#findOne(id)方法会强制提取List<Employee> employees LAZY关系。

我有使用Shop存储库的服务:

@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关系?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。

实际上我在我的实体上使用@JsonManagedReference / @ JsonBackRefernce来防止在编组到JSON时循环。它导致获取LAZY加载数据。 为避免这种情况,您应将Hibernate4Module添加到MappingJackson2HttpMessageConverter

此帖更多信息:Avoid Jackson serialization on non fetched lazy objects