Search code examples
jpaspring-data-jparelational-databaseentity-relationship

Modelling a series of elements of the same entity in JPA (one-to-one relation)


I created an entity/table for a book, and I want to achieve that each element can reference another book to create a series.

I came up with this:

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer bookId;

    @Lob
    private String text;

    @OneToOne
    @JoinColumn(name = "book_id")
    private Book previousPart;


}

However, the attribute previousPart is not seen as a column in my Database, while the others are. Is there a different annotation I have to use or is this the wrong way to model a relationship like this? Or do I have to use the type Integer instead of Book directly (I thought this was what the framework does internally)?


Solution

  • Try this way:

    @OneToOne
    @JoinColumn
    private Book previousPart;
    

    In your code you defined the book_id field as the join-column, which is an already existing column (the id itself), so actually you linked all entries to themselves.