Suggested Pages

Saturday, June 30, 2012

JPA - EntityManager : Persist Entities Part II

Persist and CascadeType.Persist


In this previous post (JPA - EntityManager : Persist Entities Part I) we have seen three examples of using of persist method from the EntityManager.
We have seen that you cannot save an entity unless you have saved its dependency beans before. In that example you could not save Child entity before having saved Parent entity.
This behaviour can be changed using CascadeType.Persist on the @ManyToOne association. This attribute performs a cascade operation of persisting parent entity when you try to persist a child entity.

Parent.java
 ...
@Entity
public class Parent {
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int parentId;
 
 @Column
 private String name;

 @OneToMany(mappedBy="parent")
 private List<Child> children;
 ...
}
    

Child.java

 ...
@Entity
public class Child {
 
 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private int childId;
 
 @Column
 private String name;
 
 @ManyToOne(cascade=CascadeType.PERSIST)
 private Parent parent;
 
 ...
}
Now when you make the following test, you won't encounter the same problem, so Child entity will be saved successfully.

GenericDAO.java
...

@Repository
public class GenericDAO {

 @PersistenceContext(unitName = "persistenceUnitTest")
 private EntityManager entityManager;


 @Transactional(propagation = Propagation.REQUIRED)
 public void save(Parent parent) {
  System.out.println("------------save(): start -------");
  entityManager.persist(parent);
  System.out.println("------------save(): end -------");
 }
 @Transactional(propagation = Propagation.REQUIRED)
 public void save(Child child) {
  System.out.println("------------save(): start -------");
  entityManager.persist(child);
  System.out.println("------------save(): end -------");
 }
}


DAOTest.java

...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "DAOTest-context.xml")
public class DAOTest {

 @Autowired
 private GenericDAO genericDAO;


 @Test
 public void testSaveEntityWithTransientAssociation() {
  System.out.println("------------testSaveEntityWithTransientAssociation(): start -------");
  Child child=new Child();
  child.setChildId(3);
  child.setName("child3");
  Parent parent = new Parent();
  parent.setParentId(3);
  parent.setName("parent3");
  child.setParent(parent);    // ManyToOne association
  genericDAO.save(child);
  System.out.println("------------testSaveEntityWithTransientAssociation(): end -------");
 }

}

No comments :

Post a Comment

Suggested Pages