Question: I have to do bulk inserts, and need the ids of what's being added. This is a basic example that shows what I am doing (which is obviously horrible for performance). I am looking for a much better way to do this.

```
public void omgThisIsSlow(final Set<ObjectOne> objOneSet,
                          final Set<ObjectTwo> objTwoSet) {
    for (final ObjectOne objOne : objOneSet) {
        persist(objOne);
        for (final ObjThree objThree : objOne.getObjThreeSet()) {
            objThree.setObjOne(objOne);
            persist(objThree);
        }
        for (final ObjectTwo objTwo : objTwoSet) {
            final ObjectTwo objTwoCopy = new ObjTwo();
            objTwoCopy.setFoo(objTwo.getFoo());                
            objTwoCopy.setBar(objTwo.getBar());
            persist(objTwoCopy);

            final ObjectFour objFour = new ObjectFour();
            objFour.setObjOne(objOne);
            objFour.setObjTwo(objTwoCopy);
            persist(objFour);
        }
    }
}

```

In the case above persist is a method which internally calls 

```
sessionFactory.getCurrentSession().saveOrUpdate();

```

Is there any optimized way of getting back the ids and bulk inserting based upon that?

Thanks!

Update: Got it working with the following additions and help from JustinKSU

```
import javax.persistence.*;
@Entity
public class ObjectFour{
  @ManyToOne(cascade = CascadeType.ALL)
  private ObjectOne objOne;
  @ManyToOne(cascade = CascadeType.ALL)
  private ObjectTwo objTwo;
}

```

// And similar for other classes and their objects that need to be persisted

Answer: 
If you define the relationships using annotations and define appropriate cascading, you should be able set the object relationships in the objects in java and persist it all in one call. Hibernate will handle setting the foreign keys for you.

Documentation - 
<http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association>

An example annotation on a parent object would be

```
@OneToMany(mappedBy = "foo", fetch = FetchType.LAZY, cascade=CascadeType.ALL)

```

On the child object you would do the following

```
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COLUMN_NAME", nullable = false)

```
I'm not sure but Hibernate makes bulk inserts/updates. The problem I understand is you need to persist the parent object in order to assign the reference to the child object.

I would try to persist all the "one" objects. And then, iterate over all their "three" objects and persist them in a second bulk insertion.

If your tree has three levels you can achieve all the insertions in 3 batchs. Pretty decent I think.