1

I'm working on a project in java with a postgresql database and I'm having a problem when I try to insert data or rather when I commit. It looks like it comes from a problem with ID (game_id) but I do not know what.

Here is the code of my entity :

@Entity
@Cacheable(true)
@Table(name = "game")
@Multitenant(MultitenantType.TABLE_PER_TENANT)
@TenantTableDiscriminator(type = TenantTableDiscriminatorType.SCHEMA, contextProperty = PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)


public class Game implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "game_id", unique = true, nullable = false)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer gameId;

    @Column(name = "game_title", length = 256)
    private String gameTitle;

    @Temporal(TemporalType.DATE)
    @Column(name = "game_released")
    private Date gameReleased;

    @Column(name = "game_img")
    private Byte[] gameImg;

    @Column(name = "game_desc", length = 3072)
    private String gameDesc;

And here's how I try to insert my data :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("projet_nintendo");
        EntityManager em = emf.createEntityManager();   
        EntityTransaction transac = em.getTransaction();
        transac.begin();



        for(int ii = 0; ii < array.length(); ii++) {
            Game g = new Game();
            g.setGameId(Conversion.stringEnInt(array.getJSONObject(ii).getString("fs_id")));
            g.setGameTitle(array.getJSONObject(ii).getString("title"));

            JSONArray test = array.getJSONObject(ii).getJSONArray("dates_released_dts");
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                Date parsedDate = dateFormat.parse(test.getString(0));
                g.setGameReleased(parsedDate);
            } catch(Exception e) { 
            }
            em.persist(g);


            System.err.println(array.getJSONObject(ii).getString("pretty_date_s"));
        }

        transac.commit();
        em.close();
        emf.close();

I have this error :

Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-69] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while extracting a value from the instance variable [gameId] in the object [database.orm.Game].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[gameId-->game.game_id]
Descriptor: RelationalDescriptor(database.orm.Game --> [DatabaseTable(game)])
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
    at test.main(test.java:79)
Caused by: Exception [EclipseLink-69] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd)

Could you tell me what I'm doing wrong?

Boris Brodski
  • 8,425
  • 4
  • 40
  • 55
Grichka
  • 53
  • 1
  • 11
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Sergei Sirik Apr 12 '19 at 17:53
  • 1
    @sergei sirik : no, I know what is a NullPointerException. ;) – Grichka Apr 12 '19 at 17:58
  • Can you be sure this isn't null? `Conversion.stringEnInt(array.getJSONObject(ii).getString("fs_id"))` – Sam Orozco Apr 12 '19 at 18:02
  • So, try to debug your code then, and see in which line exactly you are getting the exception. I think it is here `g.setGameId(Conversion.stringEnInt(array.getJSONObject(ii).getString("fs_id")));`. What do you have in `array`? Where it comes from. Check this [mcve] – Sergei Sirik Apr 12 '19 at 18:02
  • @SamOrozco Yes I am sure. – Grichka Apr 12 '19 at 19:12
  • 1
    @SergeiSirik I read each attribute of my object "game" and nothing is to null everything is well informed. The error comes on line 79 which is the transac.commit (); – Grichka Apr 12 '19 at 19:12
  • @Grichka can you change the gameId data type to be primitive that way you know you're not setting a null. – Sam Orozco Apr 12 '19 at 21:09
  • @SamOrozco I just tried but it does not change anything ! I also tried to em.find an entry of my database added directly in sql from pgAdmin and it does not work either. I still have a nullPointerException error still on the primary key : Exception in thread "main" java.lang.NullPointerException at org.eclipse.persistence.internal.jpa.CMP3Policy.createPrimaryKeyFromId(CMP3Policy.java:224) at org.eclipse.persistence.internal.jpa.EntityManagerImpl.findInternal(EntityManagerImpl.java:797) ... – Grichka Apr 12 '19 at 21:28
  • Debug this line and see what is causing it? `org.eclipse.persistence.internal.jpa.CMP3Policy.createPrimaryKeyFromId(CMP3Policy.java:224) at ` – Sam Orozco Apr 12 '19 at 21:29
  • KeyElementAccessor[] pkElementArray = this.getKeyClassFields(); Object[] primaryKey = null; if (getDescriptor().getCacheKeyType() != CacheKeyType.ID_VALUE) { primaryKey = new Object[pkElementArray.length]; } Line 224 is : primaryKey = new Object[pkElementArray.length]; pkElementArray is null but I don't know why ! – Grichka Apr 12 '19 at 22:50
  • Please, show us your `getGameId()` and `setGameId()` methods. – Boris Brodski Sep 17 '20 at 03:57

2 Answers2

0
try(EntityManager em = emf.createEntityManager();   
    EntityTransaction transac = em.getTransaction()){

    ...
}
// don't need to close here em.. emf..
Boris Brodski
  • 8,425
  • 4
  • 40
  • 55
Frret
  • 1
  • 1
  • 1
    Welcome to StackOverflow! Thank you for the answer. I reformated it a bit, so the code is looking nicer. I used "Code Sample" button with "{}" icon. Please, use "Edit" button to provide some explanations to you code snippet. Thank you! – Boris Brodski Sep 17 '20 at 03:30
0

Try to remove your @GeneratedValue. Currently you are using

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

This results in the database assigns a new value automatically for your id field and then EclipseLink have to retrieve it.

Boris Brodski
  • 8,425
  • 4
  • 40
  • 55