簡體   English   中英

Java JPA 雙向多對一映射不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM