Either do something like this:
City city = new City(1);
session.save(city);
Street street = new Street(2);
session.save(street);
Peron p = new Person(city, street);
session.save(p);
session.flush();
Or setup cascading to cascade the save
operation. For example, with annotations:
@Entity
public class Person {
@Id @GeneratedValue
private Long id;
@ManyToOne(cascade = CascadeType.PERSIST) // or ALL to cascade all operations
private City city;
// ...
}
And then the code becomes:
City city = new City(1);
Street street = new Street(2);
Person p = new Person(city, street);
session.save(p);
session.flush();
References
- JPA 1.0 specification
- Section 3.2.1 "Persisting an Entity Instance"
- Section 9.1.22 "ManyToOne Annotation"
- Hibernate Core Reference Guide
- Hibernate Annotations Reference Guide