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

时间:2017-05-19 14:25:18

标签: java hibernate jpa spring-boot

我有两个班级:

@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执行的语句数量并提高性能?

谢谢

1 个答案:

答案 0 :(得分:3)

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

如果这是一对多关联,我建议您使用双向映射。因为这种情况你不需要第三个表。所以(简而言之),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/