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?

mrom
  • 83
  • 6
  • 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. – Alan Hay May 13 '16 at 09:51
  • @alanhay, I've added the code involved in calling the repo's method. – mrom May 13 '16 at 12:34
  • Are you using Spring Data Rest. Is your controller a `@RepositoryRestController`? If so: http://stackoverflow.com/questions/30910996/spring-jpa-repository-ignoring-fetchtype-lazy – Alan Hay May 13 '16 at 17:53
  • @alan, thank you for help. Your link was helpful. – mrom May 14 '16 at 17:35

1 Answers1

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

Community
  • 1
  • 1
mrom
  • 83
  • 6