Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

spring - Prevent Hibernate from generating duplicate foreign keys on table?

Our site uses Spring (5.2.8.RELEASE), Hibernate (5.4.19.Final), Tomcat (8.5.x), and SQL Server (2014). Recently, we noticed that the performance is bad in case of deleting a simple record. We found out that it is caused by duplicate foreign keys that were generated by Hibernate. When there is a new table or field, we let Hibernate generate needed new tables or keys (primary key or foreign key) by setting

hibernate.hbm2ddl.auto=update

This is only a one-time deal. After generating new tables or new keys, we prohibit Hibernate from updating any tables or keys by setting

hibernate.hbm2ddl.auto=none

However, hibernate.hbm2ddl.auto=update generates duplicate foreign keys on existing tables. For example, the site allows people to leave comments and upvote/downvote comments. Upvote/downvote table has references to Comment and Account tables, recording which comment was upvoted/downvoted and who did the vote.

Here is the code about the relationship between Vote and Account in Java. In CommentVote.java

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "account")
private Account account;

In Account.java:

@OneToMany(mappedBy = "account", targetEntity = CommentVote.class, 
fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<CommentVote> commentVotes; 

Here is what is shown in SQL Management Studio:

enter image description here

In the above picture, foreign key FK17o46... and FKmgsaf... are duplicates. For example, the foreign keys on the Account field:

enter image description here

enter image description here

If we delete the two duplicate keys and set hibernate.hbm2ddl.auto=update, then the they will be generated again. How can we prevent Hibernate from generating duplicate foreign keys if they already exist on tables while still letting it generating keys only for NEW tables or NEW fields?

question from:https://stackoverflow.com/questions/65871419/prevent-hibernate-from-generating-duplicate-foreign-keys-on-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...