Save error message: null PK instance was incorrectly provided for search operation

I am trying to use Netbeans 7.01 to learn the JSF 2.0 tutorial and JPA. I am using oracle XE and JDBC_6. I used JSF pages from the Object Wizard to create my JSF pages. Everything works fine, since I can extract data from the database and display it. However, when I try to create or update a record in the database, I get this error:

Invalid PK instance provided for search operation

How is this caused and how can I solve it?

+6
source share
3 answers

This means that you have done the following:

Entity entity = em.find(Entity.class, null); 

Note that PK is null here. To fix the problem, just make sure it is not null .

+9
source

Perhaps this is due to the fact that you are performing a search operation on an object that has not yet been saved. In this situation, the @ID field (if it is auto-generated) will not have a value, i.e. it will be zero. Then you try to find the object, and as @BalusC points out, you send a null value to your search method.

+4
source

This means that when you try to save the entity, you send the PK of the object as null.

So, you have three options:

  • Define manually PK for Entity.
  • If your database uses a type like Serial (Informix, MS SQLSERVER, etc.), then the value will automatically depend on RDMS, you can use the IDENTITY strategy, so now you can pass a null value to your pk object.

     @Entity public class Inventory implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; 
  • If your database uses sequences to generate pks (Oracle, Postgresql, etc.), then the value will be provided by the sequence so you can use:

     @Entity public class Inventory implements Serializable { @Id @GeneratedValue(generator="InvSeq") @SequenceGenerator(name="InvSeq",sequenceName="INV_SEQ", allocationSize=5) private long id; 

For more information, you can see: http://wiki.eclipse.org/EclipseLink/Examples/JPA/PrimaryKey

+2
source

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


All Articles