简体   繁体   中英

Spring and JPA 2.0 - Single value Primary Key through OneToOne

I have a simple table (ActivityLog) and I want it to have a PK that is also a FK to another table (User).

It seems to be a common thing to have, and I tried to follow this wikibook Primary Keys through OneToOne and ManyToOne Relationships . The example there involved a composite key. I need just a primitive key, so I ended up with:

@Entity
public class User {
 @Id
 private Long id;

 // other stuff
}

@Entity
public class ActivityLog {
 @Id
 @OneToOne(optional = false)
 @JoinColumn(name="user_id", referencedColumnName="id")
 private User user;

 // other stuff
}

Unfortunately i am getting:

Caused by: java.lang.IllegalArgumentException: This class [class com.example.ActivityLog] does not define an IdClass
at org.hibernate.metamodel.internal.AbstractIdentifiableType.getIdClassAttributes(AbstractIdentifiableType.java:183)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation$IdMetadata.<init>(JpaMetamodelEntityInformation.java:253)

I tried to annotate ActivityLog with:

 @IdClass(Long.class)

(even though from what I understand it is applicable only for composite keys), yet I am getting the exact same error.

Is my case different than what's on the mentioned wikibook?

Is Spring at fault here? (As suggested in this question? (no accepted answers)).

This should help:

@Entity
public class ActivityLog {

   @Id
   @Column(name = "user_id")
   private Long id;

   @OneToOne(optional = false)
   @JoinColumn(name="user_id", referencedColumnName="id")
   private User user;

   // other stuff
}

Btw. I would expect, that you need more logs per user, so you would probably need some additional (generated) id anyway ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM