Hibernate集合缓存问题

时间:2011-06-23 09:54:34

标签: java hibernate collections

我有以下2个Hibernate entites:

@Entity
@Table(name = "VEHICLE_BRAND")
public class VehicleBrand implements java.io.Serializable {

  ...

  @Column(name = "NAME", nullable = false, length = 1000)
  public String getName() {
    return name;
  }

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "vehiclebrand")
  public Set<VehicleModel> getVehicleModels() {
    return vehicleModels;
  }

  ...

}

@Entity
@Table(name = "VEHICLE_MODEL")
public class VehicleModel implements java.io.Serializable {

  ...

  @Column(name = "NAME", nullable = false, length = 1000)
  public String getName() {
    return name;
  }

  @ManyToOne(fetch=FetchType.LAZY)
  @JoinColumn(name="VECHILE_BRAND_ID")
  public VehicleBrand getVehicleBrand() {
    return this.vehicleBrand;
  }

  ...

}

我有以下测试VehicleBrand和VehicleModel的单元测试:

DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
txDef.setName("test1");
txDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus txStatus = txManager.getTransaction(txDef);

// Load brand "1" object.
VehicleBrand brand = (VehicleBrand) factory.getVehicleBrandDAO().findFirstByName("1");
assertNotNull(brand);

// Check if model "X" exists for brand "1" through collection.
Set<VehicleModel> models = brand.getVehicleModels();
for (final VehicleModel model : models) {
  assertFalse(model.getName().equals("X"));
}

// Add model "X" to brand "1".
VehicleModel model = new VehicleModel();
model.setName("X");
model.setValidFrom(new Date());
model.setVehicleBrand(brand);
factory.getVehicleModelDAO().create(model);

txManager.commit(txStatus);

txDef = new DefaultTransactionDefinition();
txDef.setName("test2");
txDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
txStatus = txManager.getTransaction(txDef);

// Check that model is added to database.
model = (VehicleModel) factory.getVehicleModelDAO().findFirstByName("X");
assertNotNull(model);
assertEquals(model.getVehicleBrandId().longValue(), 1L);

// Check if model X exists for brand "1" through collection.
brand = (VehicleBrand) factory.getVehicleBrandDAO().findFirstByName("1");
models = brand.getVehicleModels();
boolean found = false;
for (final VehicleModel model2 : models) {
  if (model2.getName().equals("X")) {
    found = true;
  }
}
assertTrue(found);

txManager.commit(txStatus);

有人可以解释为什么最后一行失败了吗?

1 个答案:

答案 0 :(得分:1)

它肯定会失败,因为您在同一事务中执行所有这些操作,因此始终从会话高速缓存返回相同的VehicleBrand实例。

由于您在创建VehicleModel时忘记了维护关联的两面(即您将品牌分配给新模型,但忘记将创建的模型添加到品牌的模型集合中),同一组模型是总是返回,并且不包含新创建的模型。