Issue
I have two classes :
@Entity
@Table(name="folder")
public class Folder{
@Id
public String reference;
@OneToMany(cascade = {CascadeType.ALL}, orphanRemoval = true)
public List<Client> clients= new ArrayList<>();
public Date createDate;
}
and the second class:
@Entity
@Table(name = "client")
public class Client implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int id;
public String name;
}
in my database i created an intermadiate table
create table folder_clients (folder_ref varchar(20) not null, clients_id int not null)
alter table folder_clients add constraint UK_clientid unique (clients_id)
alter table folder_clients add constraint FK_idClient foreign key (clients_id) references client
alter table folder_clients add constraint FK_refFolder foreign key (folder_ref) references folder
now i have a service that persists a folder, so automatically it persists all clients related to it, and this is done throught a Folder Repository:
folder.getClients().add(client);
folderRepository.save(folder);
Everything is good and working, but when i execute the SQL Profiler i find that it executes many statements, which affect performance.
Is there a better way to improve my code, in order to reduce number of statements executed by hibernate and improve performance ?
thank you
Solution
Is there many-to-many association or one-to-many association between client and folder in that case?
If that is one-to-many association, I suggest you use bidirectional mapping. Because you don't need the third table for this situation. So (briefly), fewer queries will be generated by hibernate and the performance will increase.
@Entity
@Table(name="folder")
public class Folder {
@Id
private String reference;
@OneToMany(mappedBy="folder", cascade = {CascadeType.ALL}, orphanRemoval = true)
private List<Client> clients= new ArrayList<>();
private Date createDate;
//getters and setters
}
@Entity
@Table(name = "client")
public class Client implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
@ManyToOne
@JoinColumn(name = "folder_id")
private Folder folder;
//getters and setters
}
See this awesome post about @OneToMany relationships: https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/
But, if your case is many-to-many see: https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/
Answered By - Ady Junior
Answer Checked By - Katrina (JavaFixing Volunteer)