我正在使用 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/