且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

了解注释和JPA(休眠)

更新时间:2022-10-23 21:42:04

In addition to the cascade mentioned in Glenn Lane's answer, you also need to understand how bidirectional associations work.

They have an owner side, and an inverse side. JPA only cares about the owner side to decide which association exists between entities. The owner side is the one which doesn't have the mappedBy attribute.

Your code add depertments to the company, and workers to the departments, but it only initializes the inverse sides. You forgot to initialize the owner side:

worker1.setDepartment(department);
worker2.setDepartment(department);
...
department.setCompany(company);