java - 除非访问集合,否则 Hibernate OneToMany FetchType.LAZY 无法正常工作?

标签 java spring hibernate one-to-many

我正在使用 spring 4.1.4.RELEASE + hibernate 4.3.6.Final,这是我的实体代码:

public class BaseEntity implements Serializable {
}

public class MarketInfo extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;

    @Column(name = "market_id", unique = true, length = 15)
    private String marketId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "market")
    private List<MarketChannelGroup> channelGroups;

    public List<MarketChannelGroup> getChannelGroups() {
        return channelGroups;
    }

    public void setChannelGroups(List<MarketChannelGroup> channelGroups) {
        this.channelGroups = channelGroups;
    }

...
}

public class MarketChannelGroup extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private int id;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "market_id", referencedColumnName = "market_id")
    private MarketInfo market;
...
}

我有一个 MarketInfo,我希望当我调用它的 getChannelGroups() 方法时,它会返回列表,但是我可以看到在这种情况下没有触发 HQL 查询,看来我们必须访问该列表中的某些项目才能触发 HQL 查询,否则,MarketInfo 的 channelGroups 为空。

案例一:

System.out.println(market.getChannelGroups()); // this is working, market's channelGroups is not empty. HQL query is triggered.

// here market's channelGroups is not empty

案例二:

market.getChannelGroups(); // this is not working, market's channelGroups is still empty.HQL query is not triggered.

// here market's channelGroups is empty

案例三:

market.getIndexes().get(0).getDate(); // this is working, market's channelGroups is not empty. HQL query is triggered.

// here market's channelGroups is not empty

谁能帮忙解释一下?

最佳答案

market.getChannelGroups(); // this is not working, market's channelGroups is still empty.

发生这种情况的原因可能是由于延迟加载,market.getChannelGroups() 调用返回了一个代理。当您在返回的对象上调用方法时,将发生实际加载,在本例中是 channel 组集合。 因此,要触发将实体加载到集合中,您必须调用以下命令,例如:

market.getChannelGroups().size();

现在为什么下面的调用有效?

System.out.println(market.getChannelGroups());

如果你理解了 System.out.println() 是如何工作的,原因就会很清楚,即它是在调用传入的 toString() 方法在这种情况下相当于以下对象:

System.out.println(market.getChannelGroups().toString());

这是 println(Object) 方法的 JavaDoc:

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

关于java - 除非访问集合,否则 Hibernate OneToMany FetchType.LAZY 无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928888/

相关文章:

java - apache POI MS Office Excel 无法打开字体颜色设置 Excel 文件

java - 如何根据 HTTP header 值在 RestController 之间切换?

java - 在高峰时间,请求在 Tomcat 8 中花费太多时间

java - 在 Spring Web 中更新/通知其他用户

java - Hibernate 中 native 查询的命名参数出现奇怪的异常

反序列化时出现java.lang.NullPointerException

JAVA:与不同源文件夹下存在的相同包和类名称冲突

database - H2:如何设置默认模式和数据库?

java - 为什么 Eclipse 向我显示此错误并且找不到类?

java - 如何删除列表中的一堆对象