Annotation @ManyToMany in the same entity / table

3

My Class:

@Entity
public class Report extends  AbstractModel implements IReport {

@Column
private String nome;

@Column
private byte[] arquivoJrxml;


@ManyToMany
private List<Report> subReports;

My question:

My Report class has several SubReports, that is, many to many, because several SubReports are in several reports, my doubt is due to the annotation, taking into account that a Subreport is a report object, my precise annotation of more attributes, am I correct using using SubReport and Report in the same Class / Table?

    
asked by anonymous 25.01.2018 / 11:50

1 answer

2
  

... I am using correct SubReport and Report in the same Class / Table?

The answer to this question depends on your business rules, you need to analyze the entire context, and define whether you need a SubReport class or not. For example, if the two classes have the same attributes and are used in the same context, it's a sign that you only need one class. But if any SubReport has data (attributes) that are not present in the Report, it may be a signal that SubReport is a subclass or that it contains the Report class.

  

...

The Many to Many annotation has some attributes that are always required (jointable, joinColums, ...), but the big secret here is that you will need two collections in the same class, one representing the SubReports of one Report, and one that represents the Reports of a SubReport, after all when they are two different classes, each one has a collection that represents the Many to Many relationship. Ex.:

@ManyToMany
@JoinTable(name="report_subreport",
 joinColumns=@JoinColumn(name="id_subreport"),
 inverseJoinColumns=@JoinColumn(name="id_report")
)
private List<Report> subReports;

@ManyToMany
@JoinTable(name="report_subreport",
 joinColumns=@JoinColumn(name="id_report"),
 inverseJoinColumns=@JoinColumn(name="id_subreport")
)
private List<Report> reports;

In this code example I considered the union table to be called report_subreport, and that this table has two columns: id_report and id_subreport, which are actually a reference to the primary key of the report table, as if it were a union table of two tables but in this case it is the union of a table that relates to itself, both id_report and id_subreport point to the report table, but to different records of this table, where one of them is the report and another is the subreport.

    
26.01.2018 / 13:06