/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ejb.test.cascade;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import java.util.ArrayList;
import java.util.Collection;
import org.hibernate.ejb.test.BaseEntityManagerFunctionalTestCase;
import org.junit.Test;
import static javax.persistence.CascadeType.DETACH;
import static javax.persistence.CascadeType.REMOVE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
/**
* @author Emmanuel Bernard
*/
public class DetachAndContainsTest extends BaseEntityManagerFunctionalTestCase {
@Test
public void testDetach() {
EntityManager em = getOrCreateEntityManager();
em.getTransaction().begin();
Tooth tooth = new Tooth();
Mouth mouth = new Mouth();
em.persist( mouth );
em.persist( tooth );
tooth.mouth = mouth;
mouth.teeth = new ArrayList<Tooth>();
mouth.teeth.add( tooth );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
mouth = em.find( Mouth.class, mouth.id );
assertNotNull( mouth );
assertEquals( 1, mouth.teeth.size() );
tooth = mouth.teeth.iterator().next();
em.detach( mouth );
assertFalse( em.contains( tooth ) );
em.getTransaction().commit();
em.close();
em = getOrCreateEntityManager();
em.getTransaction().begin();
em.remove( em.find( Mouth.class, mouth.id ) );
em.getTransaction().commit();
em.close();
}
@Override
public Class[] getAnnotatedClasses() {
return new Class[] {
Mouth.class,
Tooth.class
};
}
@Entity
public static class Mouth {
@Id
@GeneratedValue
public Integer id;
@OneToMany(mappedBy = "mouth", cascade = { DETACH, REMOVE } )
public Collection<Tooth> teeth;
}
@Entity
public static class Tooth {
@Id
@GeneratedValue
public Integer id;
public String type;
@ManyToOne
public Mouth mouth;
}
}