xNeyte
xNeyte

Reputation: 622

Hibernate : Inserting data set missing parameters to null in database

When I try to insert one of my object, hibernate detects missing properties of objects in my object and sets relation to null My database is composed of :

  Hall      Usine       Users_Usines    User
  hallID    usineID     userID          userID
  usineID               usineID

In order to create a Hall, I'm using :

hall = mapper.readValue(hallData, Hall.class);
long res = hallDAO.create(hall);

And the code which is executed in the DAO is :

 Session session = HibernateUtil.getCurrentSession();
 Transaction transaction = session.beginTransaction();
 int id = (int) session.save(object);
 transaction.commit();
 session.clear();
 session.close();
 HibernateUtil.closeCurrentSession();

My problem is that my Hall has an "Usine" but the "users" properties for my "Usine" is missing so hibernates sets my Users_Usines table to empty.

I fixed a similar problem on my updates by writing statement by my own instead of using session.update(object) but I saw that INSERT statement can't support INSERT VALUES format.

How to fix it ? Thanks!

Upvotes: 0

Views: 479

Answers (1)

Naros
Naros

Reputation: 21113

The problem appears not to be hibernate related but a product of how you're populating your Hall object from this mapper, which I assume is some type of JSON library perhaps.

Have you confirmed that the hallData contains all pertinent information you need to form that relationship at the database level when hibernate inserts the data? It would seem not from what has been shown thus far.

Whenever you receive this hallData, it must be absolute and complete if you're intent is to create a brand new Hall instance in your database. Hibernate only knows about the information which you provide it, so without it, that relationship cannot be built.

If the hallData is partial and your intent is to UPDATE the existing record, then you'll need to first load the Hall from the database, merge the changes you read from the mapper into the instance and then call save. This will effectively maintain existing state and alter only the fields that were provided in the hallData.

Upvotes: 1

Related Questions