For example, I have database with table book (id, title, themeId, authorId), table author (id, name) and table theme (id, name). I dont know, should i create entity exactly like in database (and then i will have problems with join queries):
class Book {
private id;
String title;
int bookThemeId;
int bookAuthorId;
}
or create something like this:
class Book {
private id;
String title;
BookTheme bookTheme;
Author bookAuthor;
}
in second case i will have problems if authorId or themeId is null (it may be) and problems with getting from DAO in general, if i want get only books list (problems – fields is null, and very bulky builder for Book entity).
Advertisement
Answer
I would go with the second option because is more object oriented. If you go with the first option, you will need to do a second query to get the details.
@Entity
@Table(name = "books")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
//...
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "theme_id", referencedColumnName = "id")
private BookTheme bookTheme;
// ... getters and setters
}
Your id will be null when fields are not created, right? For instance, when it is saved on database, it will always have an id.