提问者:小点点

Java JPA双向ManyToOne映射不工作


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

其他现有表似乎没有问题。此外,如果我从持久性 xml 中删除这个新表及其关联对象,该应用程序启动良好。

当新表是自己添加的,没有外键join即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
);

ExistingEntity.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;

共1个答案

匿名用户

解决方案:将Fetch类型切换为Lazy,如下所示:

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


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