Home > database >  ID of java objects not synchronizing with database
ID of java objects not synchronizing with database

Time:04-20

The only link I found that's close to what I am experiencing is this one : How do you synchronize the id of a java object to its associated db row? and there's not much of a solution in it.

My problem is that my Java objects aren't updated after being added to my database despite the .commit()

    em.getTransaction().begin();
    System.out.println(eleve.getID());
    em.persist(eleve);
    em.getTransaction().commit();
    System.out.println(eleve.getID());

which refers to this class

public class Eleve {

private String _nom;
private String _prenom;
private float _ptsMerite;
@Id
private int _IDEleve;

and yields this output : 0 0

I think I've done everything properly when it comes to the persistence since it does create the object in the database (mySQL) with correct ID's which I've set to be autoincrement. I am using javax.persistence for everything (annotations and such).

CodePudding user response:

Did you try to add the @GeneratedValue annotation at your ID field?

There are four possible strategies you can choose from:

  • GenerationType.AUTO: The JPA provider will choose an appropriate strategy for the underlying database.
  • GenerationType.IDENTITY: Relies on a auto-increment column in your database.
  • GenerationType.SEQUENCE: Relies on a database sequence
  • GenerationType.TABLE: Uses a generator table in the database.

More info: https://www.baeldung.com/jpa-strategies-when-set-primary-key

If you ever change to a more powerful framework it is likely that this manages your transactions (CMT) so you can't (or don't want) commit everytime you want to access the ID for a new entity. In these cases you can use EntityManager#flush to synchronize Entity Manager with database.

  • Related