1

I'm getting this error when trying to save data into a table that contains foreign key columns.

This is my scenario I'm picking two options from two different ComboBoxes (one option from each different ComboBox), I write two strings, all this to build my object to save but when committing I get this error:

WARN SqlExceptionHelper - SQL Error: 1452, SQLState: 23000 ERROR SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (students.student, CONSTRAINT fk_student_career FOREIGN KEY (student_career) REFERENCES career (career_name) ON DELETE NO ACTION ON UPDATE NO ACTION) ERROR ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]

These are my classes I placed them in my gists repositories to make this post a little bit short.

I have followed many tutorials and read a lot of info but can't manage to make it work. I have used the cascadetype, JoinColumn and many other things but failed in all...

Please help me...

P.S.: I'm self-learning and this a practice.

AjFmO
  • 395
  • 2
  • 4
  • 18
  • I think it's better to include the full [exception StackTrace](https://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) instead! – O.Badr Jan 02 '18 at 20:35

1 Answers1

1

Change Student class mapping (I've included just the relevant part) to:

@Entity
@Table(name = "student", catalog = "students")
public class Student implements java.io.Serializable {

    ...

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "student_career",referencedColumnName="career_name" nullable = false)
    private Career career;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "student_section", nullable = false)
    private Section section;

    ...
}
  • referencedColumnName is used to explicitly map Career foreign key to the correct column career_name instead of its id career_id, check this related question for more detail.

  • CascadeType.PERSIST was added to save both to Career and Section while saving Student, if not, the database won't find the appropriate record for Student's foreign keys, (and I think, this is the origin of the SqlExceptionHelper)

O.Badr
  • 2,853
  • 2
  • 27
  • 36
  • Wow! finally! Thank you, Sr. this solved my issue! thanks a lot, I really appreciate this help! thank you pretty much! I don't know if is the best method or the best way to do it! but it worked. – AjFmO Jan 02 '18 at 23:42
  • 1
    Glad it help! `I don't know if is the best method or the best way to do it!`, write a test scenario before the implementation, and if the test passes so your approach is correct. – O.Badr Jan 03 '18 at 09:58