为什么JPA外键相关(@ManyToOne)子对象在持久化父对象时被分离

时间:2014-05-27 08:32:56

标签: java spring hibernate jpa

父对象持久化后,我的子对象将被分离。在返回父对象进行查看时,我的子对象为null。要解决此问题,我将再次从数据库中提取对象以在视图中处理。

//伪代码

家长实体

class Donor{
  @ManyToOne(fetch = FetchType.EAGER)
  private PreferredLanguage  preferredLanguage;
}

儿童实体

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package model.preferredlanguage;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 *
 * @author srikanth
 */
@Entity
public class PreferredLanguage  {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, insertable=false, updatable=false)
    private Long id;

    @Column(length=20)
    private String preferredLanguage;

    public Long getId() {
        return id;
    }

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

    public String getPreferredLanguage() {
        return preferredLanguage;
    }

    public void setPreferredLanguage(String preferredLanguage) {
        this.preferredLanguage = preferredLanguage;
    }


    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof PreferredLanguage)) {
            return false;
        }
        PreferredLanguage other = (PreferredLanguage) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

}

Crntroller AddDonor方法

savedDonor = donorRepository.addDonor(donor);

存储库方法

  public Donor addDonor(Donor donor) {
    updateDonorAutomaticFields(donor);
    em.persist(donor);
    em.flush();
    return donor;
  }

1 个答案:

答案 0 :(得分:-1)

请提供代码段,

我的猜测,您的子对象可能是FetchType FetchType.LAZY