在这里,我尝试在数据持久化到mysql
db之后获取自动生成的ID。
DTO类
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;
}
要持久化到数据库中的业务逻辑类。
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();
我尝试了不同风格的代码来从
Object
中获取自动生成的Id,该Id刚刚保存到数据库中。但没有成功。注意:-此代码工作正常,并将数据持久化到
db
(无错误)。但无法获取自动生成的ID(表中有多个引用)。到目前为止我试过的链接
jpa-returning-an-auto-generated-id-after-persist
how-to-get-id-of-last-persisted-entity-using-jpa
how-to-get-the-primary-key-of-any-jpa-entity
请帮帮我。。任何帮助都将被告知。。
谢谢您。
最佳答案
这是一个很长的机会,但我还是建议你。
您已经声明了字段private long tradetransactionid;
这是一个基元类型。这意味着它不允许空值,并且在实例化时隐式为0。在数据库中持久化对象时,尝试插入id等于0的项/对象。
您可以尝试private Long tradetransactionid;
,这是一种引用类型。这样,它最初为空,可以通过自动生成进行设置。