Search code examples
mysqldesign-patternsdto

DTO classes, represent foreign keys on multiple values


I have a question about DTO class representation. I have two tables on my database, where one has two foreign keys on another one, for example:

book(id, author_name, author_age)
author(name, age, telephone)

where book author_name and author_age are foreign keys on author name and age.

Generally what's the best way to implement this situation on a DTO class? Inside Book DTO, it's better to do something like:

public class Book {
    private String id;
    private Author author;
}

or something like

public class Book {
    private String id;
    private String author_name;
    private int author_age;
}

?


Solution

  • DTO are objects that are being used for just transfering the values over communication channel most of time over http or https.

    Note : Make your properties as public instead of private.

    We should make it as simple as possible.

    so use it like

    public class Book {
        public String id;
        public String author_name;
        public int author_age;
    }
    

    If you would compare the DTO without Author object vs DTO with Author object converted into json or xml, DTO without Author would be less in size.

    When using Author inside Book you just add extra wrapper (for author_name and author_age) which cost you some more over communication channel.

    in case if Book have multiple authors or in case of one to many relationship you need to do like:

    public class Book {
        public String id;
        public List<Author> authors;
    }
    

    Note:But make sure Author should not have a back property with Book instance like following.

    public class Author
    {
        public Book book;
    }
    

    in some client side framework like knockout it creates loop with observables.