Hi,
I am using hibernate-3.1.2 and hibernate-annotations-3.1beta8 with hsqldb-1.8.0.
In my OO I want to have (let's say) class X, class Y, and class Association, which explicitly represents the many-to-many relational association between entities X and Y.
I want the navigability to be unidirectional from Association to X (and Y), so there is not reference from X (Y) to Association
So I have something like:
Code:
@Entity
public class X {
private Long id;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
public void setId(Long id) {
this.id = id;
}
// NO references to Association
}
Code:
@Entity
public class Y {
private Long id;
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
public void setId(Long id) {
this.id = id;
}
// NO references to Association
}
Code:
@Entity
public class Association {
private Long id;
private X x; // reference to one X
private Y y; // reference to one Y
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
public void setId(Long id) {
this.id = id;
}
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REFRESH, CascadeType.MERGE},fetch= FetchType.EAGER)
@JoinColumn(name="x_id")
@Column(nullable=false)
public X getX(){
return x;
}
public void setX(X x){
this.x=x;
}
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REFRESH, CascadeType.MERGE},fetch= FetchType.EAGER)
@JoinColumn(name="y_id")
@Column(nullable=false)
public Y getY(){
return x;
}
public void setY(Y y){
this.y=y;
}
}
The issues are:
- When I delete an already saved instance of X, it does not delete automatically all the persistent instances of Association that reference that X that has been deleted, and so I have a database that is invalid indeed (because the foreign key x_id value points to something that does not exist anymore in the db)
- If a save a newly crated instance of Association which is composed on a newly created instance of (let's say) X, X is not persisted as well. If instead I change the @ManyToOne Annotation from:
Code:
@ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REFRESH, CascadeType.MERGE}
to:
Code:
@ManyToOne(cascade={CascadeType.ALL}
it performs that but has the drawback that if I delete the Association, it deletes as well the X instance, which is not what I want of course! (because it does not reflect the semantic of the model)
The DAO codes for X, Y and Association is based on the GenericDAO pattern (integrated with Spring, throught HibernateDAOSupport), which simply does:
Code:
public void saveOrUpdate(T entity) throws DataAccessException{
getHibernateTemplate().saveOrUpdate(entity);
}
public void remove(ID id) throws DataAccessException {
T o = (T) getHibernateTemplate().load(persistentClass, id);
if (o != null)
getHibernateTemplate().delete(o);
else
throw new ObjectRetrievalFailureException(persistentClass, id);
}
Which didn't give any other problem in the model.
Help would be appreciated, thanks a lot in advance.