0

I have 2 tables.. Table A contains composite primary key. I am using this key as a foreign key in another table. but in this table i need to have a composite primary key where one of the column i need to take it from the composite key of A table. I could not achieve this with mapsId as it is taking a whole CK. is there anyway to achieve it?

i just need hibernate way of doing like below:

I need exactly like this in hibernate

Anand
  • 51
  • 4

1 Answers1

0

Here is how you could map the entities corresponding to the database tables in the SO question you linked to:

@Entity
public class Concert {
  @Id
  Integer id;

  String name;

  ...
}


@Embeddable
public class ConcertDetailsId {
  Date date;

  Integer concertId; // corresponds to PK type of Concert
}


@Entity
public class ConcertDetails {
  @EmbeddedId
  ConcertDetailsId id;

  @MapsId("concertId") // maps concertId attribute of embedded id
  @ManyToOne
  Concert concert;

  BigDecimal cost;

  ...
}

Is this how you tried to use @MapsId? If so, what was the problem?

Derived identities are discussed (with examples) in the JPA 2.2 spec in section 2.4.1.

Brian Vosburgh
  • 3,146
  • 1
  • 18
  • 18
  • In my case concert has a composite key where I need one column of it not the whole ck.. I will use this column and other column in another table as ck – Anand Jan 30 '20 at 05:27
  • So, that is *not* "exactly" like the tables you linked to in your question. : ) If the `ConcertDetails` foreign key uses only a single field in `Concert`, that field must be unique in the `Concert` table. Is that correct? If so, you simply use that single field as the `Concert` primary key (for Hibernate). – Brian Vosburgh Jan 30 '20 at 23:38
  • my bad, i have linked a wrong one.. sorry on that. assume that the concert has composite key containing 2 field.. i want to use only 1 field of it as a primary key on another table.how is that possible? – Anand Jan 31 '20 at 06:50
  • As I mentioned in my earlier comment, if the `Concert` field is *unique* by itself (which it would have to be for your `ConcertDetails` foreign key to work), you might be able to get away with putting an `@Id` annotation on only that single field and leave the other half of the primary key as a `@Basic` mapping. – Brian Vosburgh Feb 01 '20 at 01:59