Reputation: 83
I have following relationship:
@Entity class Shop {
@OneToMany(mappedBy = "shop", fetch = LAZY)
private List<Employee> employees = new LinkedList<>();
}
and
@Entity class Employee {
@ManyToOne
private Shop shop;
}
I've declared Spring Data repository like this:
public interface ShopRepository extends JpaRepository<Shop, Long> {}
Calling ShopRepository#findOne(id)
method forces fetching of the List<Employee> employees
which is LAZY
relationship.
I have service which uses Shop repository:
@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);
}
} The service method is called within another controller method:
@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;
}
}
How to get rid of fetching employees
relationship?
Upvotes: 3
Views: 2498
Reputation: 83
I found solution.
Actually I used @JsonManagedReference/@JsonBackRefernce on my entity to prevent cycling while marshaling to JSON. It causes fetching LAZY loading data.
To avoid this you should add Hibernate4Module
to MappingJackson2HttpMessageConverter
.
More info at this post: Avoid Jackson serialization on non fetched lazy objects
Upvotes: 2