There are two entities:

public class TimeOfSessionEntity { @Id @Column(name = "timeOfSessionId") private Long timeOfSessionId; @Column(name = "timeOfSession") private Timestamp timeOfSessionDate; private Long movieId; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "dateOfSessionId") private DateOfSessionEntity dateOfSession; } 

AND

 public class DateOfSessionEntity { @Id @Column(name = "dateOfSessionId") private Long dateOfSessionId; @Column(name = "dateOfSessionTime") private Timestamp dateOfSession; @OneToMany(mappedBy = "dateOfSession", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<TimeOfSessionEntity> timeOfSession = new HashSet<>(); } 

When I save the TimeOfSessionEntity entity to the database , the entry automatically references the DateOfSessionEntity table with id = 0. those. I want to first create an entry in TimeOfSessionEntity, and then select which id to reference in DateOfSessionEntity. what am I doing wrong? When saving TimeOfSessionEntity, I do not specify a foreign key.

  • See how the column is defined in the database. It looks like it is not null default 0 - talex
  • @talex looked, the default value of null is worth - Alex
  • Riddle. Try to breakpoint set. It is necessary to understand who puts the value there. Hiberneit himself should not do this. - talex
  • @talex Why should not, and who will do it? - Roman C

1 answer 1

The id value is usually generated in Hibernate. It would be necessary to put an annotation @GeneratedValue .

In more detail you can read about this annotation here .

The value of the foreign key is set if you save both objects, or alternatively, then the dependent object is taken from the session.