我有两个类:
@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 Profiler时,发现它执行了许多语句,这会影响性能。
有没有更好的方法来改进我的代码,以减少Hibernate执行的语句数量并提高性能?
谢谢。
List<Client> clients= new ArrayList<>();
如果Client
不是一个实际的类? - XtremeBaumer@JoinColumn
来摆脱中间表。这将减少写入次数,但可能会(或可能不会,具体取决于您的用例)对查询性能和/或更新产生负面影响。 - crizzis