[英]Java JPA bidirectional ManyToOne mapping not working
我正在尝试在现有表和新表之间设置一个新的 JPA 双向映射。 它似乎不起作用。 实体管理器在运行时不会初始化。
其他现有表似乎没有问题。 此外,如果我从持久性 xml 中删除此新表及其关联的 object,则该应用程序启动正常。
该应用程序也可以正常工作,当新表自己添加时,没有外键连接即。 OneToMany 或 ManyToOne 映射。
有人可以帮我确定缺少什么吗?
例外指出:
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);
}
}
}
新实体.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<>();
我不确定 fetch 样式如何导致这种差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.