为什么外键没有保存在级联创建中?

时间:2017-11-29 15:38:19

标签: java spring hibernate jpa

我有两个实体

@Entity
@Table(name = "groups")
public class Group {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private Company company;

    ...
}

@Entity
public class Company {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
    private Set<Group> groups = new HashSet<>();

    public void addGroup(final Group group) {
        groups.add(group);
    }

    ...
}

如果我单独保存每一个,那么一切都很好

Company company = companyRepository.save(new Company());

Group group = new Group();
group.setName("Managers");
group.setCompany(company);
groupRepository.save(group);

但是,如果我试图在Hibernate的肩膀上转移组的创建

Group group = new Group();
group.setName("Managers");

Company company = new Company();
company.addGroup(group);
companyRepository.save(company);

然后使用空company字段

创建组
db=> select * from groups;
 id |      name      | company_id
----+----------------+------------
  1 | Admins         |
  2 | Managers       |
  3 | Operators      |

我希望Hibernate能够建立关系。我做错了吗?

0 个答案:

没有答案