gpt4 book ai didi

Java JPA 双向 ManyToOne 映射不起作用

转载 作者:行者123 更新时间:2023-12-01 21:14:12 24 4
gpt4 key购买 nike

我正在尝试在现有表和新表之间设置一个新的 JPA 双向映射。这似乎不起作用。实体管理器不会在运行时初始化。

其他现有表似乎可以正常工作。另外,如果我从持久性 xml 中删除这个新表及其关联对象,应用程序启动正常。

当新表自行添加时,无需外键连接,该应用程序也可以正常工作。一对多或多对一映射。

有人可以帮我确定缺少什么吗?

注意到异常:

ERROR SomeService:104 - General Error: Something wrong happened in JVM
java.lang.NoClassDefFoundError: Could not initialize class com.java.path.persistence.DefaultEntityManager

CREATE TABLE IF NOT EXISTS new_entity (
id BIGSERIAL PRIMARY KEY,
existing_tbl_id BIGINT NOT NULL
);

现有实体:

CREATE TABLE IF NOT EXISTS existing_entity (
id BIGSERIAL PRIMARY KEY
);

现有实体.java

@Entity
@Table(name = "existing_entity")
public class ExistingEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@OneToMany(mappedBy = "existingEntity",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private List<NewEntity> newEntities = new ArrayList<>();


public List<NewEntity> getNewEntities() {
return newEntities;
}

public void setNewEntities(List<NewEntity> newEntities) {
newEntities.forEach(newEntity ->
newEntity.setExistingEntity(this)
);
this.newEntities = newEntities;
}

public void addNewEntities(NewEntity newEntity) {
if (newEntity != null) {
newEntity.setExistingEntity(this);
newEntities.add(newEntity);
}
}
}

NewEntity.java

@Entity
@Table(name = "new_entity")
public class NewEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "existing_tbl_id")
private ExistingEntity existingEntity;

public ExistingEntity getExistingEntity() {
return existingEntity;
}

public void setExistingEntity(ExistingEntity existingEntity) {
this.existingEntity = existingEntity;
}

}

我也尝试过以下方法,但不起作用:

    @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "existing_tbl_id", referencedColumnName = "id")
private ExistingEntity existingEntity;

最佳答案

解决方案:将 Fetch 类型切换为 Lazy 的操作如下:

    @OneToMany(mappedBy = "existingEntity", 
cascade = CascadeType.ALL,
fetch = FetchType.LAZY)
private List<NewEntity> newEntities = new ArrayList<>();


我不确定提取样式如何导致这种差异。

关于Java JPA 双向 ManyToOne 映射不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886368/

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