Hi, please help with the following issue.
I have two entities:
Code:
@Entity
@Table(name="SHOPPING_SESSIONS")
public class ShoppingSession {
...
@ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY)
@JoinColumn(name="WEB_SESSION_ID", nullable=false)
private WebSession webSession;
...
}
@Entity
@Table(name="WEB_SESSIONS")
public class WebSession {
@Id
@Column(name="WEB_SESSION_ID", updatable=false)
private String id;
...
@OneToMany(mappedBy="webSession" cascade=CascadeType.REFRESH, fetch=FetchType.LAZY)
@JoinColumn(name="WEB_SESSION_ID")
private Set<ShoppingSession> shoppingSessions;
...
}
Now, this is typical code performed when new shopping cart is created in eshop (unlimited shopping session may be created in one web session):
Code:
ShoppingSession shoppingSession = new ShoppingSession();
if (webSession == null) {
webSession = new WebSession();
webSession.setId(request.getSession().getId());
}
shoppingSession.setWebSession(webSession);
When shopping cart is being saved the persist() method is called for save ShoppingSession to the DB. Hibernate calls INSERT on both SHOPPING_SESSIONS and WEB_SESSIONS tables.
Now, the new shopping cart (ShoppingSession entity) is created in the same web session and the first above code is perfomed again. In this time the once saved WebSession is set to the newlly created ShoppingSession. When I try to save the new ShoppingSession, Hibernate calls INSERT on WEB_SESSIONS again. This call fails because unique WEB_SESSION_ID constraint.
Please help me with this situation and advice correct solution.
Thank you very much.