Reputation: 846
In my spring mvc app I have doctor and user tables in database. Every doctor has a user. The problem is when I try to update doctor, the user that belongs to doctor is not being updated. Instead of this I see a new user in my database that belongs to the updated doctor.
Here is my Doctor.java entity:
@Entity
@Table(name="doctor")
public class Doctor {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name="name")
private String name;
@Column(name="tel")
private String tel;
@Column(name="email")
@Email
private String email;
private transient String ConfirmPassword;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private User user;
//getter and setters....
And here is my User.java entity
@Entity
@Table(name="user")
public class User {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
//getters and setters...
}
Here is my form:
<form:form action="save" modelAttribute="doctor" method="post">
<form:errors path="name"></form:errors>
<form:input path="name" placeholder="Doktor İsmi" class="form-control" />
<form:input path="user.username" placeholder="Kullanıcı Adı" class="form-control" />
<form:input type="email" path="email" placeholder="Email" class="form-control" />
<form:input path="tel" placeholder="Telefon" class="form-control" />
<form:input type="password" path="user.password" placeholder="Şifre" class="form-control" />
<form:hidden path="id" />/>
<input type="submit" value="Doktor Kaydet" />
</form:form>
Here is controller save method :
@PostMapping(value="/save")
public String save(@Valid Doctor dr, @Valid User usr, BindingResult bindingResult){
doctorValidator.validate(dr, bindingResult);
if (bindingResult.hasErrors()) {
return "admin/doctor-form";
}
else{
dr.getUser().setIs_doctor(1);
doctorService.save(dr);
return "redirect:list";
}
}
Finally here is DoctorDAO. Save method, I dont have extra save operation for user, because it should be saved via doctor.
public void save(Doctor dr) {
Session s = sessionFactory.getCurrentSession();
s.saveOrUpdate("doctor", dr);
}
I tried to read references, I have read examples and so on. I am beginner to Hibernate and JEE platform. I could not find a solution in two days.
Thanks,,
Upvotes: 2
Views: 1558
Reputation: 26522
I would do it this way:
public void save(Doctor dr) {
Session s = sessionFactory.getCurrentSession();
Doctor managedDr = s.merge(dr);
managedDr.getUser().setIs_doctor(1);
s.saveOrUpdate("doctor", managedDr);
}
Now, during merge, the User entity will fetched and when you perform the saveOrUpdate, it should update the user instead of inserting as the id will be there.
Upvotes: 1