Skip to content

Instantly share code, notes, and snippets.

@stliu
Created June 13, 2011 08:11
Show Gist options
  • Save stliu/1022451 to your computer and use it in GitHub Desktop.
Save stliu/1022451 to your computer and use it in GitHub Desktop.
Session s = openSession();
s.beginTransaction();
Apple a1 = new Apple();
a1.name = "a1";
Bug b1 = new Bug();
b1.name = "b1";
a1.bugs.add( b1 );
s.persist( a1 );
Apple a2 = new Apple();
a2.name = "a2";
Bug b2 = new Bug();
b2.name = "b2";
a2.bugs.add( b2 );
s.persist( a2 );
Apple a3 = new Apple();
a3.name="a3";
s.persist( a3 );
s.getTransaction().commit();
s.close();
s = openSession( );
s.beginTransaction();
Bug b = (Bug)s.get( Bug.class, b1.id );
List apples = s.createQuery( "select a from Apple a join fetch a.bugs" ).list();
for(Object obj:apples){
Apple a = (Apple)obj;
if(a.bugs.contains( b )){
a.bugs.remove( b );
if(a.bugs.isEmpty()){
s.delete( a );
}
}
}
s.delete( b );
s.getTransaction().commit();
s.close();
---------------------
@Entity
public class Apple {
@Id
@GeneratedValue
Long id;
String name;
@ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH })
@JoinTable(name = "APPLE_BUGS",
joinColumns = @JoinColumn(name = "TID"),
inverseJoinColumns = @JoinColumn(name = "EXID"))
List<Bug> bugs = new ArrayList<Bug>();
}
-----------------------
/**
* @author Strong Liu
*/
@Entity
public class Bug {
@Id
@GeneratedValue
Long id;
String name;
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Bug bug = (Bug) o;
if ( name != null ? !name.equals( bug.name ) : bug.name != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment