I have a springboot application using hibernate and I'm trying to run a native query to insert into the table societate_uses_conts. The fields societate_id and cont_id are both foreign keys.

I have the following attempt:

    Query insertQuery = entityManager.createNativeQuery("insert into societate_uses_conts (societate_id, cont_id) values ( ?, ?)")
            .setParameter(1, 1)
            .setParameter(2, 1);
    insertQuery.executeUpdate();

This works fine, inserts the right values.

I have the second attempt:

    Query insertQuery = entityManager.createNativeQuery("insert into societate_uses_conts (societate_id, cont_id) values ( ?, ?)")
            .setParameter(1, 1L)
            .setParameter(2, 1L);
    insertQuery.executeUpdate();

This throws the following exception:

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`contab_resource`.`societate_uses_conts`, CONSTRAINT `FK620nuyuxnu39nketctadg8c0m` FOREIGN KEY (`cont_id`) REFERENCES `conts` (`id`))

Both fields are made from Entities, and have the type Long. I need to insert Long values in the native query.

So why is this and how can I solve it?

0 Answers