开发者

How to reserve a set of primary key identifiers for preloading bootstrap data

We would like to reserve a set of primary key iden开发者_开发技巧tifiers for all tables (e.g. 1-1000) so that we can bootstrap the system with pre-loaded system data.

All our JPA entity classes have the following definition for the primary key.

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false, insertable = false, updatable = false)
private Integer id;

is there a way to tell the database that increments should start happening from 1000 (i.e. customer specific data will start from 1000 onwards). We support (h2, mysql, postgres) in our environment and I would prefer a solution which can be driven via JPA and reverse engineering DDL tools from Hibernate.

Let me know if this is the correct approach


You could try the TABLE strategy instead of IDENTITY. From the Hibernate book:

Much like Hibernate’s hilo strategy, TABLE relies on a database table that holds the last generated integer primary key value, and each generator is mapped to one row in this table. Each row has two columns: pkColumnName and valueColumnName. The pkColumnValue assigns each row to a particular generator, and the value column holds the last retrieved primary key. The persistence provider allocates up to allocationSize integers in each turn.

Here is an example with more explanation. And a more complex example for setting the initial value.

You could also try using a custom sequence generator, defined in your orm.xml, like this:

<sequence-generator name="mySequenceGenerator"
  sequence-name="MY_SEQUENCE"
  initial-value="123"
  allocation-size="20"/>

This declares that a database sequence named MY_SEQUENCE with an initial value of 123 can be used as a source for database identifier generation, and that the persistence engine should obtain 20 values every time it needs identifiers. (Note, though, that Hibernate Annotations, at the time of writing, ignores the initialValue setting.)

To apply this identifier generator for a particular entity, use its name:

@Entity
class name MyEntity {
  @Id @GeneratedValue(generator = "mySequenceGenerator")
  String id;
}


If everything else fails, you can always write your own custom ID generator and use it in your DAO's create(Entity entity) method. The ID sequence table could be something like

-------------------------------------------------------------
| sequence_name | initial_value | current_value | increment |
-------------------------------------------------------------
|           foo |          1001 |          2000 |       100 |

This could mean that IDs for table foo start at 1001 and are incremented by 100 (so you don't have to call DB for each new table insert).

That's what we're using without much problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜