My data has a many to many relationship between
stocks and
tanks.
It is mapped in an intervening table
mapstock2tanks which has some additional data about the relationship between each specific pair. The identity of an element in the mapping table is the pair
stockId and
tankId.
At some point in my code i want to remove all such mappings between a particular stock
s and all tanks. In the code, it appears as if the operation is a success, but when the transaction is complete, the relationships are still there.
On to the details. Here is a snippet of code within the transaction:
Code:
System.out.println("Before:" + s.getMapstock2tankses().size());
s.getMapstock2tankses().clear();
System.out.println("After: " + s.getMapstock2tankses().size());
the stock in question was in two tanks so as expected, the out put is
Before: 2
After: 0
But no change happens in the database. As an aside, other operations on attributes of the stock
s in the same transaction context are carried out as expected, so s.setComment("foo") does indeed change the comment attribute of
s.
The Hibernate mapping of the relationship is like this from the Stock's point of view:
Code:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "stock")
public Set<Mapstock2tanks> getMapstock2tankses() {
return this.mapstock2tankses;
}
And from the Tank's point of view:
Code:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "tank")
public Set<Mapstock2tanks> getMapstock2tankses() {
return this.mapstock2tankses;
}
And in the mapping table we have this stuff:
Code:
...
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride(name = "stockId", column = @Column(name = "stockId", nullable = false)),
@AttributeOverride(name = "tankId", column = @Column(name = "tankId", nullable = false)) })
public Mapstock2tanksId getId() {
return this.id;
}
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "stockId", nullable = false, insertable = false, updatable = false)
public Stock getStock() {
return this.stock;
}
...
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "tankId", nullable = false, insertable = false, updatable = false)
public Tank getTank() {
return this.tank;
}
Yes, if it seems to you like the code comes from the Hibernate Tools code generator, you are right.
Anyway, it is unclear to me why the relationships are not going away, even though they appear to be gone within the java code.
In another part of my application, I use a straight many to many hibernate relationship modeled in an intervening table with no additional fields (i.e. just id pairs), and things are working just fine. I also have another one to many relationship which I am able to update jut fine as well. But I am clearly not understanding something fundamental in what I am doing here.
Any help would be much appreciated.
Ted