gpt4 book ai didi

java - JPA - 当多对一关系中存在父级时保存元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:56 25 4
gpt4 key购买 nike

我有两个实体,Branch 和 Enterprise,这两个实体扩展了一个 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);
}

我需要帮助。

最佳答案

为什么Enterprise的原因是不受管理的我不清楚。它可能根本不会持久化,也可能是从其他持久化上下文中分离或获取的。

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

如果在此之前没有持久化为了拥有Enterprise坚持时坚持Branch你需要启用 CascadeType.PERSIST在其 @ManyToOne注释

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

您也可以尝试启用 CascadeType.MERGE .这有点取决于你的原因 Enterprise被视为独立

关于java - JPA - 当多对一关系中存在父级时保存元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com