Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top