我有两个实体,Branch和Enterprise,这两个实体扩展了AbstractEntity
AbstractEntity
@Id
@Column(length=36)
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
分公司实体:
private String name;
private int code;
@ManyToOne
@JoinColumn(name = "enterprise_id")
private Enterprise enterprise;
企业实体
private String name;
private String nit;
private String sheetconfig;
@OneToMany(cascade = CascadeType.ALL,
mappedBy = "enterprise", orphanRemoval = true)
private List<Branch> branches = new ArrayList<Branch>();
当我尝试保存分支时,我在组合框中选择企业并发送请求但我得到以下错误:
object references an unsaved transient instance - save the transient instance before flushing : com.gettecob.gestcart.model.Branch.enterprise
注意:企业列表存在,只需要用企业关联保存分支。
bean配置:
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DriverManagerDataSource dataSource) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setPackagesToScan(new String[]{"com.gettecob.gestcart.*"});
entityManagerFactoryBean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("hibernate.hbm2ddl.auto", "create");
jpaProperties.put("hibernate.show_sql", "true");
jpaProperties.put("hibernate.format_sql", "true");
jpaProperties.put("hibernate.use_sql_comments", "true");
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
entityManagerFactoryBean.setJpaPropertyMap(jpaProperties);
return entityManagerFactoryBean;
}
Branch Repository保存方法
public Branch save(Branch branch) {
return em.merge(branch);
}
我需要帮助。
Enterprise
无法管理的原因我不清楚。它可能根本不存在,或者可能是从其他持久化上下文中分离或获得的。
例如,如果您将新实体的id
设置为模仿现有实体,则可能会发生这种情况,因为持久性上下文应该处理设置id
。
如果在此之前没有持久化以便在持久化Enterprise
时持续存在Branch
,则需要在其CascadeType.PERSIST
注释中启用@ManyToOne
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name = "enterprise_id")
private Enterprise enterprise;
您也可以尝试启用CascadeType.MERGE
。这取决于你的Enterprise
被认为是分离的原因。