JPA: ID generation using a Sequence

Note : Using a monotonic increasing sequence in an Oracle RAC Env may be the root cause for a major Performance problem .

For Details read:

Create table and Create Sequence Script :

drop table logemp2;
create table logemp2 ( LOGID number, EMPNO number(4),  message varchar(40) );
alter table logemp2 add CONSTRAINT  logemp2_pk  PRIMARY KEY (logid);
desc logemp2;

drop sequence SEQ_LOGEMP2;
create sequence SEQ_LOGEMP2  minvalue 1 maxvalue 9999999999999999999999999999
  start with 1 increment by 1;

Entity JAVA code;
public class Logemp2 implements Serializable
    {
    private static final long serialVersionUID = 1L;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Id
    @SequenceGenerator(name="SEQ_GEN", sequenceName="SEQ_LOGEMP2", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_GEN")
    @Basic(optional = false)
    @NotNull
    @Column(name = "LOGID")
    private BigDecimal logid;
    @Column(name = "EMPNO")
    private Short empno;
    @Size(max = 40)
    @Column(name = "MESSAGE")
    private String message;

Java code to write a record 
    private void writeLog(Emp2 e, String m, EntityManager em) throws Exception
      {
      String methodName = "writelog()";
      short eno =  e.getEmpno();
      Logemp2 l = new Logemp2();
      l.setEmpno(e.getEmpno());
      // l.setLogid() is serviced by our database sequence
      l.setMessage(m);
      try
        {
        em.persist(l);
        } 
       catch ( Exception e1)
          {             
            setRunTimeInfo("Error writing LOG RECORD in " + methodName + " - Error: " + e1.getMessage() );         
            genericException( "Error writing LOG RECORD in " +methodName  , e1);
          }   
      }

Leave a Reply

Your email address will not be published. Required fields are marked *