@OneToOne Or @ManyToOne?

164 Views Asked by At

can somebody confirm me following?

I have following Entites:

public class Book {

.............


}


public class Student {

@OneToOne
Book favoriteBook
}

public class StudentOrderHistory{

Student student;

@OneToOne
Book lastBook;
}

In case if favoriteBook / lastBook is linked only to each one Student or StudentOrderHistory is both then still a @OneToOne relation or would it a @ManyToOne Relation because the same BookEntity is linked in several Entites (here Student and StudentOrderHistory)?

Is it correct that @ManyToOne would be more in case e.g the same book is the favoriteBook for different Students?

1

There are 1 best solutions below

2
On

I assume that many students could have the same favourite book, this makes it a many-to-one:

public class Student {
   @ManyToOne
   Book favoriteBook
}

This means that two different students can have the same book as their favourites. Example: John and Jane favourite book is "Moby Dick"

Unless a Student can have multiple order histories, I would say that that's a one-to-one:

public class StudentOrderHistory{

    @OneToOne
    Student student;
}

Because the history of orders is unique for each students.

Not sure about lastBook though. If it means that a student has the book and nobody else can have it as lastBook, than it's a one-to-one:

public class StudentOrderHistory{

    @OneToOne
    Student student;

    @OneToOne
    Book lastBook;
}

This book only belongs to this StudentOrderHistory and therefore to a single student. If you mean the last book they've ordered and in the meanwhile, somebody else has ordered the same book, than it's a many-to-one:

public class StudentOrderHistory{

    @OneToOne
    Student student;

    @ManyToOne
    Book lastBook;
}

It seems that two different students could order the same book, but without knowing more it's hard to say which solution is correct.