1

I have a problem in Hibernate when updating an object which contains a collection of another object. Here's what it looks like:

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

  @OneToMany(targetEntity = Car.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "garage", orphanRemoval = true)
  public Set<Car> getCars() {
    return cars;
  }

}

Then there is the Car class:

@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;
  }

}

The garage then has a service:

@Transactional
public class GarageService {

  public void updateGarage(Session session, Garage garage) {
    session.update(garage);
  }

}

Now lets say I have in my database a garage with a white, blue and red car.

|  GarageId  |
|      1     |

|  CarId  |  Color  |  GarageId  |
|    1    |  white  |     1      |
|    2    |  blue   |     1      |
|    3    |  red    |     1      |

If I call my update method with the same garage but with only a blue and a red car, the update is successful. The database removed the white car from the Car table.

|  CarId  |  Color  |  GarageId  |
|    2    |  blue   |     1      |
|    3    |  red    |     1      |

However, if I call my update method with the same garage but with an empty collection of cars, no car gets deleted from the Car table.

Any ideas what I might be doing wrong?

JimmyB
  • 12,101
  • 2
  • 28
  • 44

0 Answers0