JPA: How to improve performance in persistance of OneToMany relationships

Viewed 5192

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

2 Answers

Making the one to many relationship bi-directional helps and by default it is eager fetch. In many cases you would need Eager fetch, but making type fetch eager will just execute n*m(n number of parent record one to many and M is the number of children records many to one mapped) queries.

The solution is fairly simple use JPA 2.1 where you need add entiry grapgh at JPA repository only

@Repository
public interface FolderRepo extends JpaRepository< Folder, Long> {

@EntityGraph(attributePaths = {"clients")
List<Folder> findAll();
}

This will create Join between the bi-directional mapping of Folder-> Clients

Blockquote you need to override equals method in each of these entity classes with ID else this will not work. You can get rid of complex multilevel NamedEntityGraph at each entity class which is not needed if you have added.

Related