Hibernate/JPA中@ElementCollection如果沒有@OrderColumn效能會降低
@ElementCollection是Hibernate/JPA中代表父子關係的多方註釋,但是沒有@OrderColumn的@ElementCollection插入和刪除容易出現效能損失,而使用@OrderColumn效能變得更好。
本應用程式展示了沒有@OrderColumn使用@ElementCollection可能導致的效能損失。
父實體:
@Entity <b>public</b> <b>class</b> ShoppingCart implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) <b>private</b> Long id; <b>private</b> String name; @ElementCollection <b>private</b> List<String> products = <b>new</b> ArrayList<>();
這裡的@ElementCollection並沒有主鍵,@ElementCollection是對映到單獨的資料表中。當你有很多插入和刪除動作時,避免@ElementCollection,因為資料庫為了實現加入或刪除,得刪除很多現有的行。資料表中資料項越多,效能損失越大。
測試原始碼可以在這裡 找到 。
解決
通過新增@OrderColumn可以減少在集合尾部附近進行操作時的一些效能損失(例如,在集合末尾新增/刪除)。主要是,位於新增/刪除條目之前的所有元素都保持不變,因此如果我們影響靠近集合尾部的行,則可以忽略效能損失。
@Entity <b>public</b> <b>class</b> ShoppingCart implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) <b>private</b> Long id; @Column(name = <font>"name"</font><font>, nullable = false) <b>private</b> String name; @ElementCollection @OrderColumn(name = </font><font>"index_no"</font><font>) <b>private</b> List<String> products = <b>new</b> ArrayList<>(); </font>
測試原始碼可以在這裡 找到