Question

I'm saving with Hibernate a transient instance of an entity:

Student e = new Student();
e.setName("Clio");

School s = new School();
s.setName("Archimede");

e.setSchool(s);

myDao.save(e);

I've transactional dao:

@Transactional
@Repository
public class MyDao {
   // Other code

Why is in this case only the student inserted into the table but not the school?

Was it helpful?

Solution

Because you didn't pass the school to save() and school currently is not related in any way with the student.

EDIT: Since you have added the relation between student and school then you probably don't map the reference between them correctly. You probably miss the cascade option (@ManyToOne(cascade=CascadeType.PERSIST) or @ManyToOne(cascade=CascadeType.ALL)) on school reference in Student class.

OTHER TIPS

Since you did not state sth. else, I suppose that your school entity owns the relationship between school and students. Thus you have to add the students to the persistent set that resides in the school entity (e.g. school.getStudents().add(student)) and save the school entity afterwards.

For more information on relationship ownership look here. Of course you may also decide to let student own the relationship, although it makes not much sense for me in this case, than your provided code would work as expected.

You also need to add the right cascading, as stated in the previous answer

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