user2539823
user2539823

Reputation: 103

Complex relation in hibernate entities

I have following problem with relations between 3 entites: Form, FormConfig, and GroupForms. The model is manyToMany relation between Form and GroupForms, but there is some additional data associated with this join, so I modeled entity FormConfig. Form is related with FormConfig in OneToMany relation, and GroupForms is related to FormConfig in OneToMany relation. In code it looks like:

Form.java:

...
@OneToMany(mappedBy = "form", cascade = CascadeType.ALL)
private List<FormConfig> formConfigs = new ArrayList<FormConfig>();
...

GroupForms.java:

...
@OneToMany(mappedBy="group", fetch=FetchType.EAGER)
private List<FormConfig> formConfigs = new ArrayList<FormConfig>();

FormConfig:

...
@ManyToOne
@JoinColumn(name = "kf_grupa_id")
private GroupForms group;

@ManyToOne
@JoinColumn(name = "kf_formularz_id")
private Form form;
....

I created some group, and now I want to create new Form and join it to GroupForms, so:

void createFormInGroup(GroupForms groupForms) {
   Form form = new Form();
   /*setters execution*/    
   form.set(..);
   ....
   FormConfig formConfig = new FormConfig();
   /*setters execution*/
   formConfig.set(..);
   ....
   formConfig.setGroup(groupForms);
   formConfig.setForm(form);
   form.getFormConfigs().add(formConfig);
   groupForms.getFormConfigs().add(formConfig);

   /* code responsible for beginTransaction */
   session.saveOrUpdate(formConfig);
   session.saveOrUpdate(form);
   session.saveOrUpdate(groupForms);
   /* code responsible for endTransaction */
}

I call this function two times, for one groups, which means that I want to create two forms and those forms should be in one group. But unfortunately, query using hibernate, returns me two rows in entity GroupForms. I check my tables, and there is only one row in table associated with entity GroupForms. Can anyone help with that? I do not have idea why hibernate returns more GroupForms than exist in database.

Regards

Upvotes: 2

Views: 308

Answers (1)

Alan Hay
Alan Hay

Reputation: 23226

This most likely caused by the following:

@OneToMany(mappedBy="group", fetch=FetchType.EAGER)

See here for further discussion:

Hibernate Criteria returns children multiple times with FetchType.EAGER

and my answer to a similar question here:

Hibernate and criteria that return the same items multiple times

Upvotes: 2

Related Questions