Navdeep Singh
Navdeep Singh

Reputation: 689

How to update referenced entity in hibernate

I have following tables

Question_Table:{
quesId int primary key,
statusid int reference to Status_Table.statuId
}


Status_Table:{
statusId int primary key
}

Answers_Table:{
index int primary key,
quesId int reference to Question_Table.quesId,
answerDescription varchar
}
  1. Question have multiple Answers here: Question_Table--Answer_Table have One-to-Many Relationship.
  2. Every Question have its status id: Question_Table--Status_Table have Many-to-One Relationship

Query: On update of answer in answer_table by end user i want to update its status : "Complete" in question_table, but when i fire update(answer) it only fire update on answer table (verified in logs) , i am confused with the situation as here i do not have direct relation between entities-- status and answer table.

Upvotes: 0

Views: 387

Answers (2)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

When working with object within the Hibernate session (attached objects), you don't need to call update. Hibernate finds the changes.

pseudocode:

answer = session.CreateQuery("select ...")
answer.Question.Status = Completed;
session.Commit();

Changes are sent to the database on commit (or when flushing before queries).

Upvotes: 0

RAS
RAS

Reputation: 8158

You won't be able to update status_id in Question's table by just doing update(answer);.

Firstly you need to fetch the record from Question table, that is associated with the answer. After that you need to fire an update query to the fetched question record with the new status_id.

For example,

  1. update(answer);
  2. if answer.question_id = 1, then do: select * from question where id = 1
  3. set status in question & then do: update(question);

Upvotes: 1

Related Questions