Search code examples
javahibernatehibernate-mapping

Foreign key mapping to Embeddable class


I am using Hibernate to join Entity1 to Entity2 where Entity2 have a composite primary key.

Entity2 contains 2 columns id and type

public class Entity2 {
  @EmbeddedId
  private Entity2PK id;
}
@Embeddable
public class Entity2PK implements Serializable {
  @Column(name = "id")
  private String id;

  @Column(name = "type")
  private String type;
}

Entity1 contains 2 columns id and entity_2_id (foreign key ref to Entity2)

public class Entity1 {
  @Id
  @Column(name = "id", updatable = false, nullable = false)
  private String id;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name="entity_2_id")
  private Entity2 entity2;
}

All the calls are failing because of this. Does anyone have a solution for this ?

Error Message:

org.hibernate.AnnotationException: A Foreign key refering Entity2 from Entity1 has the wrong number of column. should be 4
    at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:646)
    at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:102)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1814)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1758)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1646)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:286)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:473)
    at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:84)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)

Solution

  • You seem to have the same problem as this user: AnnotationException: A Foreign key refering has the wrong number of column. should be 2

    Entity1 can not store the relationship in one single column, because Entity2 has an id with 2 columns. You can solve this by using JoinColumns instead of JoinColumn.

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns({
      @JoinColumn(name = "entity2_id", insertable = false, updatable = false),
      @JoinColumn(name = "entity2_type", insertable = false, updatable = false)
    })
    private Entity2 entity2;