-
1. Re: generating a Primary Key using a Sequence in JPA
ashusri000 Jun 26, 2007 3:57 AM (in response to ashusri000)CORRECTION in above Post :
Hi All ,
I have a simple POJO where I want to generate the Primary key using a sequence that increments value by 1 each time a new row gets inserted , .Here is the sample code:
public class Tab1 implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "tabGen")
@SequenceGenerator(name="tabGen" , allocationSize=1)
@Column(name="ID")
private long id;
But the problem with this is that it increments the value by 2 and not by 1 . Please can anybody help me out . -
2. Re: generating a Primary Key using a Sequence in JPA
waynebaylor Jun 26, 2007 9:33 AM (in response to ashusri000)are you using the sequence to generate keys for other entities?
-
3. Re: generating a Primary Key using a Sequence in JPA
ashusri000 Jun 27, 2007 12:28 AM (in response to ashusri000)Hi ,
What I am trying to do is , simply trying to persist a new Object every time the main method gets called and could not see anypoint where there are multiple / double call to sequence. The sequence that I am using is not already defined in the database , I have defined it in the code itself.
Here is the code :
import java.io.Serializable;
import java.util.HashMap;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Id;
import javax.persistence.Persistence;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
@Entity
@Table(name="TAB1")
@DiscriminatorColumn(name="ID", discriminatorType = DiscriminatorType.INTEGER)
public class Tab1 implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator = "tabGen")
@SequenceGenerator(name="tabGen" , allocationSize=1)
@Column(name="ID")
private long id;
private String val;
private static final long serialVersionUID = 1L;
public Tab1() {
super();
this.val= "hello";
}
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getVal() {
return this.val;
}
public void setVal(String val) {
this.val = val;
}
public static void main(String[] args) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("testApp", new HashMap());
EntityManager em = emf.createEntityManager();
try{
em.getTransaction().begin();
em.persist(new Tab1());
System.out.println("Done");
em.getTransaction().commit();
System.out.println("Entered the Values");
}catch (Exception e) {
e.printStackTrace();
}finally{
em.close();
}
}
}