0

I'm using Spring boot 2.0.1, I have the following entities :

    @Entity
    public class Session {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
        @ManyToOne
        private Groupe groupe;
        ...

and

@Entity
public class Groupe {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    @OneToMany(mappedBy="groupe")
    private List<Session> sessions;
    ...

I'm wondering why if I persist Group before Session it works, but not if I do the opposite, here is an example : Working case :

Groupe groupe1= new Groupe("groupe1",professor);
Session session1 = new Session(new Date(),false,groupe1);
Session session2 = new Session(new Date(),true,groupe1);
groupeRepository.save(groupe1); // <-----
sessionRepository.save(session1);
sessionRepository.save(session2);

Not working case :

Groupe groupe1= new Groupe("groupe1",professor);
Session session1 = new Session(new Date(),false,groupe1);
Session session2 = new Session(new Date(),true,groupe1);
sessionRepository.save(session1);
sessionRepository.save(session2);
groupeRepository.save(groupe1); // <-----

It gives me the following exception :

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : gestionAbs.bean.Session.groupe -> gestionAbs.bean.Groupe 

I was expecting the opposite, since the relation is mapped by Session, Session is "the owner" of the relationship, persisting session should persist groupe, but it seems that I'm wrong, anyone can explain to me why please?

Thank you

hereForLearing
  • 1,209
  • 1
  • 15
  • 33
  • 1
    Take a look here https://stackoverflow.com/a/2302814/7220980 – SlideM May 05 '18 at 21:37
  • 1
    If fact it's not the `groupeRepository.save(groupe1); // <-----` line that crashes it's the `sessionRepository.save(session1);` line that crashes because it needs the Groupe id field to save as a foreign key. – K.Nicholas May 06 '18 at 01:07
  • @SlideM thank you but what if I don't want to cascade changes, I've been told that cascading all may have some weird effects like duplicate entries etc... I think that respecting the order is my best choice for now... – hereForLearing May 06 '18 at 18:30
  • @K.Nicholas I think you're right – hereForLearing May 06 '18 at 18:30

0 Answers0