JPA - 当ParentToOne关系

时间:2017-12-16 02:27:05

标签: java spring hibernate jpa many-to-one

我有两个实体,分支和企业,这两个实体扩展为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;
}

BranchRepository保存方法

public Branch save(Branch branch) {
    return em.merge(branch);
}

我需要帮助。

1 个答案:

答案 0 :(得分:0)

Enterprise未受管理的原因对我来说并不清楚。它可能根本不存在,或者可能是从其他持久化上下文中分离或获得的。

例如,如果您将新实体的id设置为模仿现有实体,则可能会发生这种情况,因为持久性上下文应处理设置id

如果在此之前没有保留,以便在持久Enterprise时保持Branch,则需要在其CascadeType.PERSIST注释中启用@ManyToOne

@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name = "enterprise_id")
private Enterprise enterprise;

您也可以尝试启用CascadeType.MERGE。这取决于您Enterprise被视为分离的原因。