How to insert a record using the entity manager without defining a primary key field?
I tried to insert records into the database (MySQL) using entity classes and entity manager However, one of the fields is automatically incrementing the primary key, so the insertion will not succeed unless I provide the value manually
public boolean newContributor(String name,String email,String country,Integer contactable,String address) { Contributors contributor = new Contributors(); //entity class contributor.setId(??????); //this is Primary Key field and is of int datatype contributor.setName(name); contributor.setEmail(email); contributor.setCountry(country); contributor.setContactable(contactable); contributor.setAddress(address); em.persist(contributor); return true; }
How to solve this problem? Is there any way to tell the entity manager to try to insert without ID field and use null value instead
Update: This is part of the entity class that defines the ID
... @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @NotNull @Column(name = "id") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1,max = 50) ....
Solution
of course. You need to delete the @ notnull comment of the ID field in the @ entity definition and delete the line:
contributor.setId(??????);
From method newcontributor() The reason is that the @ notnull annotation enforces validation checks in the JPA stack This does not mean that the field is not null at the database level See here for a discussion of this issue
The rest of the code looks good