views:

51

answers:

2

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?


}
+1  A: 

You should persist your newly created object first, then add it to its container. Additionaly, the save method of org.hibernate.Session returns the identifier of a newly persisted object. So you just have to update your code and/or your DAO to behave like this:

newObject.setContainer(container); // facultative (only if the underlying SGBD forbids null references to the container)
Long id = (Long) hibernateSession.save(newObject); // assuming your identifier is a Long
container.add(newObject);
// now, id contains the id of your new object

Anyway, for all object with generated ids, you can always do something like this:

hibernateSession.persist(object); // persist returns void...
return object.getId(); // ... but you should have a getId method anyway
Samuel_xL
+2  A: 

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.

Pascal Thivent