2016-05-13 71 views
2

我有以下關係:避免加載延遲集合在Spring數據JPA

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

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

我已經聲明春天數據存儲庫這樣的:

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

調用ShopRepository#findOne(id)方法強制取回List<Employee> employees這是LAZY的關係。

我有一個使用店鋪倉庫服務:

@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的關係呢?

+0

我看不出這將是除非東西在你的代碼被明確觸發負荷的情況下。顯示調用回購的方法中的所有代碼。 –

+0

@alanhay,我添加了調用回購方法的代碼。 – mrom

+0

你在使用Spring Data Rest嗎?你的控制器是一個'@ RepositoryRestController'嗎?如果是這樣的話:http://stackoverflow.com/questions/30910996/spring-jpa-repository-ignoring-fetchtype-lazy –

回答

2

我找到了解決方案。

事實上,我對我的實體使用了@ JsonManagedReference/@ JsonBackRefernce,以防止封送到JSON時進行循環。它會導致讀取LAZY加載數據。 爲避免出現這種情況,您應該添加Hibernate4ModuleMappingJackson2HttpMessageConverter。在這篇文章

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