P
P
Pasechnik Kuzmich2017-11-27 17:01:06
PostgreSQL
Pasechnik Kuzmich, 2017-11-27 17:01:06

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);
    }

    ...
}

If I save each separately, then everything is fine.
Company company = companyRepository.save(new Company());

Group group = new Group();
group.setName("Менеджеры");
group.setCompany(company);
groupRepository.save(group);

And if I try to shift the creation of groups onto the shoulders of Hibernate
Group group = new Group();
group.setName("Менеджеры");

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

then groups are created with an empty company field
db=> select * from groups;
 id |      name      | company_id
----+----------------+------------
  1 | Админы         |
  2 | Менеджеры      |
  3 | Операторы      |

I was expecting Hibernate to set up the links on its own. Am I doing something wrong or is it supposed to be like this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2017-11-29
@Hivemaster

You need to explicitly assign a value to the company field:

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

and then Hibernate will do the rest.

N
Nick Smith, 2017-11-28
@Braidner

@JoinColumn(name="company_id") forgot

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question