我一直在摸不着头脑,觉得我得到了一些帮助:)
我正在使用我无法更改的旧数据库。我有以下域名:
@Entity
public class Institution {
@Id
private Long id;
@OneToMany(mappedBy="institution", fetch=FetchType.EAGER)
private List<Subscription> subscriptions = new ArrayList<Subscription>();
}
@Entity
public class Subscription {
@Id
private Long id;
@ManyToOne
@JoinColumn(name="sub_id", referencedColumnName="ins_sub_id", insertable=false, updatable=false)
private Institution institution;
}
为了简洁起见,我已经排除了显示吸气剂/制定者。没有联接表。
因此;
1)映射是否正确?我想要双向关联,我希望机构成为关系的所有者。
2)如果我加载机构,请创建new Subscription()
并将订阅添加到subscriptions
集合...
@RequestMapping(value="/add/{institutionId}", method=RequestMethod.POST)
public String submitSubscriptionForm(@ModelAttribute SubscriptionForm form) {
Institution institution = institutionService.getById(form.getInstitutionId());
Subscription subscription = new Subscription();
//...set properties on subscripton from data in the form
subscription.setInstitution(institution);
institution.getSubscriptions().add(subscription);
institutionService.saveOrUpdateInstitution(institution);
}
......当我保存机构......
institutionService.saveOrUpdateInstitution(institution);
只委托一个扩展HibernateDaoSupport的DAO。
...我收到以下错误:
org.springframework.orm.hibernate3.HibernateSystemException: Illegal attempt to associate a collection with two open sessions; nested exception is org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:737)
at com.f1000.dao.hibernate.InstitutionDaoImpl.saveOrUpdate(InstitutionDaoImpl.java:161)
我正在使用Spring并且正在使用OpenSessionInViewFilter,我无法弄清楚为什么会创建第二个会话?
答案 0 :(得分:1)
您的协会存在问题,
@ManyToOne
@JoinColumn(name="sub_id", referencedColumnName="ins_sub_id")
private Institution institution;
在insertable=false, updatable=false
内的institution
上设置Subscription
。要么您需要删除它,要么创建一个新属性,如下所示,设置为新的订阅。
private Long institutionId;
并将subscription.setInstitution(institution);
替换为
subscription.setInstitutionId(institution.getId());
有关insertable=false, updatable=false
映射的更多信息,请阅读here。