chepiov
chepiov

Reputation: 152

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:

TableB:

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]. 

Upvotes: 5

Views: 9119

Answers (2)

Mauro Molinari
Mauro Molinari

Reputation: 1407

The main problem (the exception) is not about the use of @JoinColumn rather than @PrimaryKeyJoinColumn, but what must be a limit of current Spring Data (as of 1.7.1). I also hit this problem and opened DATAJPA-649 for it. I couldn't find a workaround, rather than change the data model so that EntityB has a primary key independent from EntityA. The use of @MapsId does not help either.

Upvotes: 4

JB Nizet
JB Nizet

Reputation: 691635

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)

Upvotes: 4

Related Questions