Spring Data,JPA @OneToMany Lazy fetch在Spring Boot中不起作用

问题描述 投票:8回答:3

我有@OneToManyFabricRoll之间的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也被加载。

我想只加载FabricRollFabricDefect应该在调用函数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);
}

}

突破点:enter image description here

控制台:enter image description here

spring hibernate spring-data-jpa lazy-loading
3个回答
0
投票

您不需要使用@JoinColumn,也不需要实例化fabricDefects

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<FabricDefect> fabricDefects ; 

this问题中查看更多内容。


0
投票

FabricDefect类:

@ManyToOne
@JoinColumn(name = "fabric_roll_id")
private FabricRoll roll;

FabricRoll类:

@OneToMany(mappedBy = "roll")
private Set<FabricDefect> fabricDefects;

默认情况下,集合是懒惰加载的,只有在调用方法getFabricDefects时,JPA才会查询数据库。您可以自己查看启用日志记录。


0
投票

我在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()

© www.soinside.com 2019 - 2024. All rights reserved.