Hibernate在主键上注释一对多

时间:2014-09-26 21:53:35

标签: hibernate annotations

这里有两张桌子 - 一张用于汽车,一张用于汽车发动机的统计数据。发动机在汽车中共享,因此每个EngineStat都有多辆汽车。

我想使用hibernate在EngineStat上进行单个查询,并将所有带有该引擎的汽车作为EngineStat类的字段接收。

我认为这是一对多关系,但如果错误,请纠正我。我只想使用Java注释 - 没有.hbm.xml文件。

@javax.persistence.Entity
@javax.persistence.Table(name = "CAR", schema = "ftm")
class Car {
  @Id
  @Column(name = "car_id")
  long carId;

  @Column(name = "engine_id")
  long engineId;

  @Column(name = "model")
  ...... more stuff
}

@javax.persistence.Entity
@javax.persistence.Table(name = "ENGINE_STAT", schema = "ftm")
class EngineStat {
  @Id
  @Column(name = "engine_id")
  long engineId;

  @Column(name = "horse_power")
  ..... more stuff

  // <---- Some annotations here 
  Set<Car> cars;
}

2 个答案:

答案 0 :(得分:1)

基本想法是使用@OneToMany()

如果您愿意,可以调整提取类型以适应和省略Car

EngineStat

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "car")
 public Set<Car> cars;

Car

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "engine_id", nullable = false)
public EngineStat engineStat;

修改:要跳过对Car的修改,请在EngineStat中执行此操作:

@OneToMany
@JoinColumn(name = "engine_id")
public Set<Car> cars;

答案 1 :(得分:1)

答案比我预期的要简单(以为我在张贴之前尝试了这个,但我猜不是)。

@javax.persistence.Entity
@javax.persistence.Table(name = "CAR", schema = "ftm")
class Car {
  @Id
  @Column(name = "car_id")
  long carId;

  @Column(name = "engine_id")
  long engineId;

  @Column(name = "model")
  ...... more stuff
}

@javax.persistence.Entity
@javax.persistence.Table(name = "ENGINE_STAT", schema = "ftm")
class EngineStat {
  @Id
  @Column(name = "engine_id")
  long engineId;

  @OneToMany
  @JoinColumn(name = "engine_id")
  Set<Car> cars;

  @Column(name = "horse_power")
  ..... more stuff
}

只需将引擎ID放在主键和您的设置中即可。效果很好。