我正在使用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中的channelGroups运行良好(如果我不调用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中的解决方案不适用于我的情况。

最佳答案

将@OneToMany注释从声明移至getter方法,如下所示:

private List<MarketChannelGroup> channelGroups;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "market")
public List<MarketChannelGroup> getChannelGroups() {
    return channelGroups;
}

07-21 13:47