有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

插入查询的java空指针异常

我有我的表格国家和指标的E bean模型。 指标模型如下所示

public class Indicators extends Model {

private static final long serialVersionUID = 1L;

@Id
public Long id;

@OneToMany(mappedBy = "indicator")
public HashSet<Indicators> transactions;

@ManyToOne
@JoinColumn(name = "countryid")
public Countries country;
}

我的国家模型是这样的

    public class Countries extends Model {
          private static final long serialVersionUID = 1L;

           @Id
          @Column(name = "COUNTRYID")
          public Long countryId;

          @OneToMany(mappedBy = "country")
          public HashSet<Countries> indicators;
             }

我试图调用insert函数

  private static void procM007_SP003(ExcelInd excelRow, String indicator_code) {

    // Insert
    Indicators indObj = new Indicators();
    indObj.country.countryId=542L;
            indObj.save();

然而,indObj。国countryId导致空指针异常

感谢您的帮助。谢谢:)


共 (1) 个答案

  1. # 1 楼答案

    默认情况下,实例变量设置为null,并且由于尚未初始化对象Indicatorscountry变量,因此它将为空。因此,在空对象上设置countryId将导致NullPointerException

    您还需要初始化Indicators对象的country属性:

    Indicators indObj = new Indicators();
    indObj.country = new Countries();
    indObj.country.countryId = 542L;
    indObj.save();