Answer the question
In order to leave comments, you need to log in
Why are foreign keys not preserved when saving cascading?
I have two entities
@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("Менеджеры");
group.setCompany(company);
groupRepository.save(group);
Group group = new Group();
group.setName("Менеджеры");
Company company = new Company();
company.addGroup(group);
companyRepository.save(company);
db=> select * from groups;
id | name | company_id
----+----------------+------------
1 | Админы |
2 | Менеджеры |
3 | Операторы |
Answer the question
In order to leave comments, you need to log in
You need to explicitly assign a value to the company field:
public void addGroup(Group group) {
group.setCompany(this);
groups.add(group);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question