zwiebl zwiebl - 1 year ago 114
Java Question

Java Hibernate Many To One saving to the DB

I will jump directly to the example.

In my database, I have a table Partner, and a table Town. Those are linked in a way that each record in Partner has it's accessory

. Town doesn't know anything about the Partner.

I am trying to do my mapping, such that
objects have many-to-one relationship with the
objects, i.e. every
object has it's own
as a member variable.

In the code, that looks like the following.

@Table(name = "Town")
public class Town {

@Id // Primary Key: automatically generated
@GenericGenerator(name = "native_generator", strategy = "native")
@GeneratedValue(generator = "native_generator")
@Column(name = "Town_ID", nullable = false)
private int id;

@JoinColumn(name = "Country_ID")
private Country country;

@Column(name = "Name", nullable = false)
private String name; // ...

@Table (name = "Partner")
public class Partner {

@Id // Primary Key: automatically generated
@GenericGenerator(name = "native_generator", strategy = "native")
@GeneratedValue(generator = "native_generator")
@Column(name = "Partner_ID", nullable = false)
private int id;

@Column(name = "Type", nullable = false)
private char type;

@JoinColumn(name = "PartnerHome_ID")
private Town homeTown;

The problem

The problem occurs anytime I try to save the new Partner with the already existing Town (a Town that is already stored in the database) - it wouldn't let me, but is forcing me to save the Town once again. The example.

Town town = new Town("My town", "10000"); // already saved in the DB from before

Partner p = new Partner("New partner", town); // not yet in the DB; // If I comment on this line, the exception occurs;


So, if I don't save the town to the DB (a Town that already exists in the DB), i get the following error:

Object references an unsaved transient instance - save the transient instance beforeQuery flushing: Town

When I do save it, there is no error. Why do I need to repeatedly save objects that are already in my DB? How could I just save my new Partner object, and let it reference a town that is already in the DB?

Answer Source

If it already exists in the database, then don't create a new one. Get the one which already exists from the database:

Town alreadyExistingTown = s.get(Town.class, idOfExistingTown); 
// or Town alreadyExistingTown = s.load(Town.class, idOfExistingTown);
Partner p = new Partner("New partner", alreadyExistingTown);;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download