Search code examples
javaormjpaone-to-manypersist

Getting the ID of the persisted child object in a one-to-many relationship


I have two entity classes A and B which looks as follows.

public class A{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;    

    @OneToMany(mappedBy = "a", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
    private List<B> blist = new ArrayList<B>();

    //Other class members;

}

Class B:

public class B{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private A a;

    //Other class members;

}

I have a method which adds a B object to an A object. I want to return the id of the newly added B object.

eg:

public Long addBtoA(long aID){

            EntityTransaction tx = myDAO.getEntityManagerTransaction();

            tx.begin();
            A aObject = myDAO.load(aID);
            tx.commit();

            B bObject = new B();

            bObject.addB(bObject);

            tx.begin();
            myDAO.save(aObject);
            tx.commit();

            //Here I want to return the ID of the saved bObject.
            // After saving  aObject it's list of B objects has the newly added bObject with it's id. 
            // What is the best way to get its id?


}

Solution

  • I have a method which adds a B object to an A object. I want to return the id of the newly added B object.

    Then just do it! After the new B instance has been persisted (and the changed flushed to the database), its id has been assigned, just return it. Here is a test method that illustrates this behavior:

    @Test
    public void test_Add_B_To_A() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPu");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
    
        A a = em.find(A.class, 1L);
    
        B b = new B();
        A.addToBs(b); // convenient method that manages the bidirectional association
    
        em.getTransaction().commit(); // pending changes are flushed
    
        em.close();
        emf.close();
    
        assertNotNull(b.getId());
    }
    

    By the way, your code is a bit messy, you don't need to commit after each interaction with the EM.