Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Repository for Entity where foreign key is also primary key

I have some problems with JPA2 (EclipseLink) and Spring Data 1.4.2. In my case two tables has one-to-one relation:

TableA:

  • aId (PK)
  • ...

TableB:

  • bId (PK, FK - maps to aId in TableA)
  • ...

so I tried to do this entities:

EntityA:

@Entity
@Table(name = "TableA")
public class EntityA implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "aId")
    private Long id;
    // another fields and getter/setter/business methods
    ... 
}

EntityB:

@Entity
@Table(name = "TableB")
public class EntityB {
    @Id
    @OneToOne
    @JoinColumn(name = "bId", referencedColumnName = "aId")
    private EntityA id;
    // another fields and getter/setter/business methods
    ... 
}

Spring Data Repository for EntityA works well:

@Repository(value = "aRepository")
public interface RepositoryA extends CrudRepository<EntityA, Long> {
}

but for EntityB:

@Repository(value = "bRepository")
public interface RepositoryB extends PagingAndSortingRepository<EntityB, EntityA> {
}

throws Exception:

Expected id attribute type [class java.lang.Long] on the existing id attribute [SingularAttributeImpl[EntityTypeImpl@5270829:EntityA [....] but found attribute type [class EntityB]. 
like image 438
chepiov Avatar asked Feb 15 '23 14:02

chepiov


1 Answers

The annotation to use is @PrimaryKeyJoinColumn, not @JoinColumn:

Specifies a primary key column that is used as a foreign key to join to another table.

It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.

(emphasis mine)

like image 54
JB Nizet Avatar answered Feb 17 '23 10:02

JB Nizet