3

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?

4
  • I cannot see how that would be the case unless something in your code was explicitly triggering the load. Show all the code in the method calling the repo. Commented May 13, 2016 at 9:51
  • @alanhay, I've added the code involved in calling the repo's method. Commented May 13, 2016 at 12:34
  • Are you using Spring Data Rest. Is your controller a @RepositoryRestController? If so: stackoverflow.com/questions/30910996/… Commented May 13, 2016 at 17:53
  • @alan, thank you for help. Your link was helpful. Commented May 14, 2016 at 17:35

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.