Thursday, August 14, 2014

Table Generator in JPA

use a self-defined table for identity generation on any database, which means it is portable across databases.

1) firstly, create a table to store the id will be generated.

create table tb_id_generator (
tb_name varchar(50) not null primary key,
tb_id int(20) not null
);

insert into tb_id_generator(tb_name,tb_id) values ('table1',1);
insert into tb_id_generator(tb_name,tb_id) values ('table2',1000000);

mysql> select * from tb_id_generator;
+---------+---------+
| tb_name | tb_id   |
+---------+---------+
| table1  |           1  |
| table2  | 1000000 |
+---------+---------+
2 rows in set (0.00 sec)


2) specify strategy in entity object.

------------- PersonEO -------------

package wx.dbdemoc.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

@Entity
@Table(name = "person")
public class PersonEO implements Serializable {

private static final long serialVersionUID = 1492053620157953609L;
private Long pId;
private String name;

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "person_id_gen")
@TableGenerator(name = "person_id_gen", table = "tb_id_generator", pkColumnName = "TB_NAME", valueColumnName = "TB_ID", pkColumnValue = "table1")
public Long getpId() {
return pId;
}

public void setpId(Long pId) {
this.pId = pId;
}

@Column(name = "name")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

person_id_gen: the name of stragety
tb_id_generator: the table name to store id
table1:  to generate id for entity PersonEO

--------------- Person2EO--------------

package wx.dbdemoc.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

@Entity
@Table(name = "person2")
public class Person2EO implements Serializable {

private static final long serialVersionUID = 1492053620157953609L;
private Long pId;
private String name;

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "person_id_gen2")
@TableGenerator(name = "person_id_gen2", table = "tb_id_generator", pkColumnName = "TB_NAME", valueColumnName = "TB_ID", pkColumnValue = "table2")
public Long getpId() {
return pId;
}

public void setpId(Long pId) {
this.pId = pId;
}

@Column(name = "name")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

3)  use multiple data source, and multiple threads in single data source to run it, found it is working well in multiple threads

No comments:

Post a Comment