JPA:如何提高OneToMany关系的持久性性能

我有两节课:

@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;

}

第二类:

@Entity

@Table(name = "client")

public class Client implements Serializable {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

public int id;

public String name;

}

在我的数据库中,我创建了一个中间表

 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

现在我有一个保留文件夹的服务,因此它会自动保留与之相关的所有客户端,并且通过文件夹存储库来完成:

 folder.getClients().add(client);

folderRepository.save(folder);

一切都很好并且可以正常工作,但是当我执行SQL事件探查器时,我发现它执行了很多会影响性能的语句。

是否有更好的方法来改进我的代码,以减少hibernate状态下执行的语句数量并提高性能?

谢谢

回答:

在这种情况下,客户端和文件夹之间是否存在多对多关联或一对多关联?

如果这是一对多关联,则建议您使用双向映射。因为在这种情况下您不需要第三张表。因此(简短地),hibernate将生成较少的查询,并且性能将提高。

@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

}

看到有关@OneToMany关系的真棒帖子:https ://vladmihalcea.com/the-best-

way-to-map-a-onetomany-association-with-jpa-and-

hibernate/

但是,如果您的案例是多对多的,请参阅:https : //vladmihalcea.com/the-best-

way-to-use-the-manytomany-annotation-with-jpa-and-

hibernate/

以上是 JPA:如何提高OneToMany关系的持久性性能 的全部内容, 来源链接: utcz.com/qa/426597.html

回到顶部