How to insert records using Entity Manager without defining a primary key field?

I am trying to insert a record into a database (MySQL) using Entity Class and Entity Manager. But one of the fields is the automatically incrementing primary key, so if I did not provide the value manually, the insert would not be successful.

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 such a problem? Is there a way to tell the entity manager to try pasting without an ID field and using a NULL value instead.

Update: Here is the part of the entity class defining 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) .... 
+4
source share
1 answer

Is there any way to tell the administrator of an entity to try to insert an ID without a field and use NULL instead?

Of course. You need to remove the @NotNull annotation for the id field in the @Entity definition, and also remove the line:

 contributor.setId(??????); 

from the newContributor() method. The reason for this is that the @NotNull annotation provides validation validation on the JPA stack. This does not mean that the field is NOT NULL at the database level. See a discussion of this issue here.

The rest of the code looks fine.

+1
source

Source: https://habr.com/ru/post/1413126/


All Articles