ranger gref
ranger gref

Reputation: 49

Creating entity for database

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

Upvotes: 0

Views: 68

Answers (2)

Birju B
Birju B

Reputation: 140

I think you should go with 2nd approach. There will be no issue if your BookTheme r Author will be null if you use optional=true. For bulky builder, you can use fetchtype as lazy.

@Entity
@Table(name = "Book")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional=true)
    @JoinColumn(name = "theme_id", referencedColumnName = "id")
    private BookTheme bookTheme;

    // ... getters and setters
}

Hope, This will work!

Upvotes: 1

Patrick Santana
Patrick Santana

Reputation: 417

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.

Upvotes: 2

Related Questions