JPA - 当父级存在于ManyToOne关系中时保存元素

问题描述 投票:2回答:1

我有两个实体,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);
}

我需要帮助。

java spring hibernate jpa many-to-one
1个回答
0
投票

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.