I'm trying to persist an object to a database. Keep getting 'Column ID cannot accept null value error'. My object looks like this:
@Entity
public class TestTable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id = 0;
@Column(nullable=false, length=256)
private String data = "";
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
My persist function:
public static synchronized boolean persistObject(Object obj){
boolean success = true;
EntityManager em = null;
EntityTransaction tx = null;
try{
em = getEmf().createEntityManager();
tx = em.getTransaction();
tx.begin();
em.persist(obj);
tx.commit();
} catch (Exception e){
success = false;
} finally{
try{
em.close();
} catch(Exception e){
//nothing
}
}
return success;
}
You may use GenerationType.TABLE. That way, jpa uses a sequence table for id assigment and you may never need to generate sequence or auto-increment values or triggers that lowers portability.
Also note that in java int type is initiated with 0 default, so you may get rid of that also.