我正在使用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中的channelGroup正常工作(如果我不调用getChannelGroups(),那么channelGroups为null),但是如果我调用getChannelGroups(),则会获取每个MarketChannelGroup中的MarketInfo虽然这不应该发生,因为市场的提取模式是FetchType.LAZY。
从控制台我可以看到以下休眠日志,当我调用它的getter:
Hibernate: select channelgro0_.market_id as market_i5_12_1_, channelgro0_.id as id1_9_1_, channelgro0_.id as id1_9_0_, channelgro0_.channel_group_id as channel_2_9_0_, channelgro0_.channel_group_name as channel_3_9_0_, channelgro0_.channel_group_type as channel_4_9_0_, channelgro0_.market_id as market_i5_9_0_ from market_channel_group channelgro0_ where channelgro0_.market_id=?
Hibernate: select marketinfo0_.id as id1_12_0_, marketinfo0_.enable_flag as enable_f2_12_0_, marketinfo0_.enable_time as enable_t3_12_0_, marketinfo0_.market_id as market_i4_12_0_, marketinfo0_.market_name as market_n5_12_0_, marketinfo0_.stb_count as stb_coun6_12_0_ from market_info marketinfo0_ where marketinfo0_.market_id=?
Hibernate: select marketinfo0_.id as id1_12_0_, marketinfo0_.enable_flag as enable_f2_12_0_, marketinfo0_.enable_time as enable_t3_12_0_, marketinfo0_.market_id as market_i4_12_0_, marketinfo0_.market_name as market_n5_12_0_, marketinfo0_.stb_count as stb_coun6_12_0_ from market_info marketinfo0_ where marketinfo0_.market_id=?
Hibernate: select marketinfo0_.id as id1_12_0_, marketinfo0_.enable_flag as enable_f2_12_0_, marketinfo0_.enable_time as enable_t3_12_0_, marketinfo0_.market_id as market_i4_12_0_, marketinfo0_.market_name as market_n5_12_0_, marketinfo0_.stb_count as stb_coun6_12_0_ from market_info marketinfo0_ where marketinfo0_.market_id=?
有人可以帮忙吗?
更新
没有针对ManyToOne注释的可选方法,因此OneToOne中的解决方案对我的案例不起作用。
答案 0 :(得分:0)
将@OneToMany批注从声明移到getter方法,如下所示:
private List<MarketChannelGroup> channelGroups;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "market")
public List<MarketChannelGroup> getChannelGroups() {
return channelGroups;
}
答案 1 :(得分:0)
您的配置存档如何?看看您是否使用过滤器 OpenEntityManagerInViewFilter 。如果您正在使用它,那么总是调用方法Lazy getChannelGroups(),hibernate将在每个元素中获取。
答案 2 :(得分:0)
如果@id在getter上,则必须使用oneToMany注释来获取。惰性工作,但是如果您或某个框架在该转换中获得了惰性属性,则get方法将触发选择。