vendredi 15 septembre 2017

Using polymorphism or not hibernate mapping to Single Table

I have created simple design to ease explanation, here is the UML :

enter image description here

here is the Attachment class code :

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("Attachment")
@Table(name = "ATTACHMENTS")
public class Attachment {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ID")
    private long id;

    @ManyToOne
    @JoinColumn(name = "USER_ID")
    private User user;
...
}

and for the BookAttachment class :

@Entity
@DiscriminatorValue("BookAttachment")
public class BookAttachment extends Attachment{

    @ManyToOne
    @JoinColumn(name="Book_ID")
    private Book book;
    ...
    }

My question here, how can I do the bidirectional relation in the Book class ? should it be done like this? ( it's not polymorphism and not sure if it's good design )

public class Book{

    @OneToMany(mappedBy = "book", cascade = CascadeType.PERSIST)
    private List<BookAttachment> bookAttachments;
...
}

or the following : I don't know yet how can I use the mappedBy as the attachment class don't have relation to Book.

public class Book{

    @oneToMany
    private List<Attachment> bookAttachments;
...
}

is not using polymorphism in this example good? Book class shouldn't be related to userAttachment. ( The example is just to provide a clear understanding of how the design will be. it's not a real one, so I need to understand if not using polymorphism, in this case, is good or bad design).

Aucun commentaire:

Enregistrer un commentaire