1

更新包含另一个对象集合的对象时,我在 Hibernate 中遇到问题。这是它的样子:

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

}

然后是 Car 类:

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

}

然后车库有一项服务:

@Transactional
public class GarageService {

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

}

现在假设我的数据库中有一个带有白色、蓝色和红色汽车的车库。

|  GarageId  |
|      1     |

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

如果我用同一个车库但只有一辆蓝色和一辆红色的汽车调用我的更新方法,则更新成功。数据库从 Car 表中删除了白色汽车。

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

但是,如果我使用同一个车库但使用空的汽车集合调用我的更新方法,则不会从 Car 表中删除任何汽车。

有什么想法我可能做错了吗?

4

0 回答 0