带有EmbeddedId的中间表导致StackOverflow

时间:2010-01-18 12:36:59

标签: java hibernate

使用EmbeddedId我的hibernate映射存在问题。我的代码如下:

清单:

public class Inventory {

private Long id;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "inventory_id")
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

private Set<InventoryUser> inventoryUser = new HashSet<InventoryUser>();

@OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER, mappedBy = "pk.inventory")
public Set<InventoryUser> getInventoryUser() {
    return inventoryUser;
}

public void setInventoryUser(Set<InventoryUser> productUser) {
    this.inventoryUser = productUser;
}
}

用户:

@Entity
@Table(name = "User_Table")
public class User implements Comparable{
private String id;

@Id
@Column(name = "user_id")
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

private Set<InventoryUser> inventoryUser = new LinkedHashSet<InventoryUser>();

@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.user")
public Set<InventoryUser> getInventoryUser() {
    return inventoryUser;
}

public void setInventoryUser(Set<InventoryUser> inventoryUser) {
    this.inventoryUser = inventoryUser;
}

InventoryUser

@Entity
@Table(name = "Inventory_User")
public class InventoryUser {    
private ProductUserPK pk = new ProductUserPK();

@EmbeddedId
@NotNull
public ProductUserPK getPk() {
    return pk;
}

public void setPk(ProductUserPK pk) {
    this.pk = pk;
}

@Embeddable
public static class ProductUserPK implements Serializable {
    public ProductUserPK(){

    }

    private User user;

    @ManyToOne
    @JoinColumn(name = "user_id", insertable = false, nullable = false)
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
        // this.user.getInventoryUser().add(InventoryUser.this);

    }

    private Inventory inventory;

    @ManyToOne
    @JoinColumn(name = "inventory_id", insertable = false, nullable = false)
    public Inventory getInventory() {
        return inventory;
    }

    public void setInventory(Inventory inventory) {
        this.inventory = inventory;

    }

现在持久化数据工作正常,但是当我搜索库存时,我总是得到一个StackOverflow,即使数据库中只有一个条目。

任何想法是什么意思?

电贺 克里斯

3 个答案:

答案 0 :(得分:0)

在没有额外细节的情况下进行攻击......看起来您的Inventory对象急切地获取InventoryUser,其中包含ProductUser的主键,其中包含Inventory。这是循环的,可能会导致您的溢出。

答案 1 :(得分:0)

我认为这是因为InventoryUser和ProductUserPK之间的循环引用。

InventoryUser.pk或ProductUserPK.user都应该是懒惰的。

答案 2 :(得分:0)

嗯,好像它与标准搜索有关。我尝试了一个简单的hql语句,我的工作...... 谢谢你的回复,我把我放在正确的路上;)