Hibernate/JPA批插入中使用PostgreSQL的(BIG)SERIAL自增主鍵
在PostgreSQL中使用GenerationType.IDENTITY會失效批處理能力。因此使用其(BIG)SERIAL,它的作用類似MySQL的 AUTO_INCREMENT。
這裡使用GenerationType.SEQUENCE啟用批插入處理,通過hi/lo演算法優化它。
第一步,使用GenerationType.SEQUENCE替代GenerationType.IDENTITY:
@Entity <b>public</b> <b>class</b> TennisPlayer implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id <font><i>// This will disable insert batching - AVOID IT! 會失效批處理</i></font><font> </font><font><i>// @GeneratedValue(strategy = GenerationType.IDENTITY)</i></font><font> </font><font><i>// This will work, but better use the below solution 效能不佳</i></font><font> </font><font><i>// @GeneratedValue(strategy = GenerationType.AUTO)</i></font><font> </font><font><i>// This will allow insert batching and optimizes the identifiers</i></font><font> </font><font><i>// generation via the hi/lo algorithm</i></font><font> @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = </font><font>"hilo"</font><font>) @GenericGenerator(name = </font><font>"hilo"</font><font>, strategy = </font><font>"org.hibernate.id.enhanced.SequenceStyleGenerator"</font><font>, parameters = { @Parameter(name = </font><font>"sequence_name"</font><font>, value = </font><font>"sequence"</font><font>), @Parameter(name = </font><font>"initial_value"</font><font>, value = </font><font>"1"</font><font>), @Parameter(name = </font><font>"increment_size"</font><font>, value = </font><font>"10"</font><font>), @Parameter(name = </font><font>"optimizer"</font><font>, value = </font><font>"hilo"</font><font>) }) <b>private</b> Long id; </font>
這裡依靠hi/lo演算法在一次資料庫往返中獲取多個識別符號:
原始碼可以在 這裡 找到 。