DavidZemon
DavidZemon

Reputation: 531

Hibernate Annotate One-to-many on Primary Key

Two tables here - one for cars, and one for stats on engines in cars. Engines are shared across cars, so there are multiple cars for every EngineStat.

I'd like to use hibernate to make a single query on EngineStat and receive all cars with that engine as a field of the EngineStat class.

I believe this is a one-to-many relationship, but do please correct me if that is wrong. I would like to use Java annotations only - no .hbm.xml file.

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

Upvotes: 0

Views: 64

Answers (2)

DavidZemon
DavidZemon

Reputation: 531

The answer is simpler than I expected (thought I tried this before posting, but I guess not).

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

Simply put engine ID in there as BOTH the primary key and your set. Works great.

Upvotes: 1

Brian
Brian

Reputation: 3914

The basic idea is to use @OneToMany():

Adjust fetch type to suit and omit from Car if you wish.

In EngineStat:

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

In Car

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

Edit: To skip the modification to Car, do this in EngineStat instead:

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

Upvotes: 1

Related Questions