Vikrant Kashyap Vikrant Kashyap - 5 months ago 10
MySQL Question

How to get auto generated Id after persist into the mysqlDB Using JPA

Here I have tried to get auto Generated ID after data is persist in

mysql
db.


DTO Class


public class TradeTransaction {

private long tradetransactionid ;
private long borrowerid ;
private String operationalcountry ;
private String productcategory ;
private String producttype ;
private boolean ishazardous;
private boolean specialisedHandle;
private String currency;
private double transactionvalue;
private String suppliercountry;

@Id
@Column
public long getTradetransactionid() {
return tradetransactionid;
}
@Column
public long getBorrowerid() {
return borrowerid;
}



Business Logic Class To persist into the Database.


EntityManager v_objEm;
EntityTransaction v_objTran;
TradeTransaction v_ObjectToPersist;
v_ObjectToPersist = new TradeTransaction();

v_ObjectToPersist.setBorrowerid(25);
v_ObjectToPersist.setOperationalcountry("India");
v_ObjectToPersist.setProductcategory("electornics");
v_ObjectToPersist.setProducttype("E9088"));
v_ObjectToPersist.setIshazardous(true);
v_ObjectToPersist.setSpecialisedHandle(true);
v_ObjectToPersist.setCurrency("usd");
v_ObjectToPersist.setTransactionvalue(2000.3);
v_ObjectToPersist.setSuppliercountry("african-based");
v_objEm = MyCustomClass.getEntityManager();
v_objTran = v_objEm.getTransaction();
v_objTran.begin();

v_objEm.persist(v_ObjectToPersist);
System.out.println(v_ObjectToPersist.getTradetransactionid()); //Transaction ID print as Zero.
v_objTran.commit();
System.out.println(v_ObjectToPersist.getTradetransactionid()); //Transaction ID print as Zero Here Too.

//v_objEm.refresh(v_ObjectToPersist); //not Working throwing Exception.
v_objEm.close();


I have tried different flavor of code to get auto generated Id from the
Object
which is just persisted into the database. but didn't succeed.

Note :- This code is working fine and persisting the data into the
db
(No Error). But Won't be able to get auto generated ID (which is a
primary key
have multiple reference in tables).
Links that I have tried So Far


  1. jpa-returning-an-auto-generated-id-after-persist

  2. how-to-get-id-of-last-persisted-entity-using-jpa

  3. how-to-get-the-primary-key-of-any-jpa-entity



Please help me out.. Any Help will be appriciated..

Thank You.

Answer

This is a long shot, but I'll suggest it anyway.

You have declared the field private long tradetransactionid; which is a primitive type. This means it does not allow nulls and is implicitly 0 on instantiation. When you persist the object in the database, you try to insert an item/object with id equal to 0. You could try private Long tradetransactionid;, which is a reference type. This way it is initially null and can be set by auto-generation.