Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jpa repository save method returns different id from the one inserted into database

I'm using spring data (jpaRepository) + Oracle 11g Database.

Here's the code of my JUnit test:

@Test
    public void testAjoutUtilisateur() {
    Utilisateur utilisateur = new Utilisateur();

(...)

    utilisateur=repository.save(utilisateur);

    Utilisateur dbutilisateur = repository.findOne(utilisateur.getIdutilisateur());
    assertNotNull(dbutilisateur);

When I debug I find that "utilisateur" object returned by repository.save method has an id like "2100" while the corresponding inserted line in the database have an id like "43".

I have an Oracle database with a sequence and a trigger to have the auto incremented property for the id for my "Utilisateur" table.

Here is the id definition in my Utilisateur entity:

@Entity
@NamedQuery(name="Utilisateur.findAll", query="SELECT u FROM Utilisateur u")
@SequenceGenerator(sequenceName="ID_UTILISATEUR_SEQ", name="ID_UTILISATEUR_SEQ")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ID_UTILISATEUR_SEQ")
private Long idutilisateur;

Where is the problem? Is it within the save method?

Thank you.


Edit:

I figured out that the problem was already solved by the solution of @jhadesdev and the data lines I was talking about were inserted when the triggers were actives.

Finally, I have to mention that by default the JUnit test seems to not insert data in the database (it inserts then rollback). In order to invalidate this behaviour we have to specify the @TransactionConfiguration(defaultRollback=false) annotation in the test class.

For example (in my case):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:context/dao-context.xml" })
@TransactionConfiguration(defaultRollback=false)
@Transactional
public class UtilisateurRepositoryTest {

Hope it can help someone.

like image 744
Sinda MOKADDEM Avatar asked Feb 14 '23 06:02

Sinda MOKADDEM


1 Answers

The problem is that two separate mechanisms are in place to generate the key:

  • one at Hibernate level which is to call a sequence and use the value to populate an Id column and send it to the database as the insert key
  • and another mechanism at the database that Hibernate does not know about: the column is incremented via a trigger.

Hibernate thinks that the insert was made with the value of the sequence, but in the database something else occurred. The simplest solution would probably be to remove the trigger mechanism, and let Hibernate populate the key based on the sequence only.

like image 54
Angular University Avatar answered Feb 17 '23 21:02

Angular University