我有@OneToMany
和FabricRoll
之间的FabricDefect
关系。
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "fabric_roll_id", referencedColumnName = "fabric_roll_id")
private Set<FabricDefect> fabricDefects = new HashSet<>();
问题是当我通过FabricRoll
函数获得JpaRepository
时
找到所有()
同事FabricDefect
也被加载。
我想只加载FabricRoll
和FabricDefect
应该在调用函数getFabricDefect()
时加载
FabricRollServiceImpl类
@Component
public class FabricRollServiceImpl implements IFabricRollService{
@Autowired
FabricRollRepository fabricRollRepository;
@Transactional(propagation = Propagation.REQUIRED)
@Override
public List<FabricRoll> getAllFabricRoll() {
FabricRoll fabricRoll1 = new FabricRoll();
fabricRoll1.setBatchNo("34344");
fabricRoll1.setLotNo("425");
fabricRoll1.setPoNo("42");
fabricRoll1.setRollLength(2343);
fabricRoll1.setRollNo("356");
fabricRoll1.setRollWidth(60);
fabricRoll1.setStyleNo("354");
FabricDefect fabricDefect = new FabricDefect();
fabricDefect.setDefectNote("note");
fabricDefect.setDefectPoint(3);
fabricDefect.setSegment(3);
fabricDefect.setYard(42);
Set<FabricDefect> fabricDefects = new HashSet<>();
fabricDefects.add(fabricDefect);
fabricRoll1.setFabricDefects(fabricDefects);
addFabricRoll(fabricRoll1);
FabricRoll fabricRoll = null;
return fabricRollRepository.findAll();
}
@Override
public void addFabricRoll(FabricRoll fabricRoll) {
fabricRollRepository.save(fabricRoll);
}
}
您不需要使用@JoinColumn
,也不需要实例化fabricDefects
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<FabricDefect> fabricDefects ;
在this问题中查看更多内容。
FabricDefect类:
@ManyToOne
@JoinColumn(name = "fabric_roll_id")
private FabricRoll roll;
FabricRoll类:
@OneToMany(mappedBy = "roll")
private Set<FabricDefect> fabricDefects;
默认情况下,集合是懒惰加载的,只有在调用方法getFabricDefects
时,JPA才会查询数据库。您可以自己查看启用日志记录。
我在this tutorial找到了解决方案。
你必须修改FabricRoll
OneToMany
地图如下:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fabricRoll")
private Set<FabricDefect> fabricDefects;
FabricDefect
ManyToOne
如下(如果你将fabric_roll_id
字段包含在你的实体中,请记得删除它):
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fabric_roll_id")
private FabricRoll fabricRoll;
而且你不需要在@Transactional(propagation = Propagation.REQUIRED)
函数之前添加getAllFabricRoll()
。