0
votes

I have a problem in Hibernate when updating child table When a duplicate record comes the parent table record gets updated but a new column gets inserted in child table, where as the child table also needs to be updated and not inserted. Using session.saveOrUpdate(storeObject)

Have tried cascade presist, SaveOrUpdate, but the issue is not resolved

@Entity
@Table(name = "Garage")
public class Garage {

@OneToMany( mappedBy = "garage")
@Cascade(CascadeType.PERSIST)
  public Set<Car> getCars() {
    return cars;
  }

}

@Entity
@Table(name="Car", uniqueConstraints=@UniqueConstraint(columnNames={"GarageId"}))
public class Car {

  private Garage garage;

  @ManyToOne(optional=false)
  @JoinColumn(name="GarageId")
  public Garage getGarage() {
    return garage;
  }

}
1
writing a proper equals and hashcode method would probably solve this IMHO. - Abdullah Khan

1 Answers

0
votes

I was also facing the same issue.I searched a lot, but couldn't get a proper way to update the data in child table while inserting new data in the parent.Finally, I just did a hack to meet my need.Get the child item by mapped id and delete all the rows and insert again.A snippet of code that I have used to writing below.

for (Car car: garag.getCars()) {
    String hql4 = "delete from Car where garage.garageId=:id";
    Query<EventDetails> query4 = session.createQuery(hql4);
    query4.setParameter("id", garageid);
    query4.executeUpdate();
    }

Try this.It may help you.