gpt4 book ai didi

java - 在 Hibernate 中添加 Employee 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 05:30:50 25 4
gpt4 key购买 nike

我有一个 Hibernate 实体“Intranet”,其中包含以下代码:

// Imports removed

@Entity
@Table(name = "intranets", uniqueConstraints = @UniqueConstraint(columnNames = "company_name"))
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Intranet {

@Id
@Column(name = "INTRANET_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private int intranetId;

@Column(name = "owner_id")
private int ownerId;

@Column(name = "setup_done")
private boolean isSetUp = false;

@Column(name = "company_name")
private String companyName;

@ElementCollection
@CollectionTable(name = "employees")
@Column(name = "employee")
private List<Integer> employeeIds;


public int getIntranetId() {

return intranetId;
}

public void setIntranetId(int intranetId) {

this.intranetId = intranetId;
}

public boolean isSetUp() {

return isSetUp;
}

public void setSetUp(boolean isSetUp) {

this.isSetUp = isSetUp;
}

public String getCompanyName() {

return companyName;
}

public void setCompanyName(String companyName) {

this.companyName = companyName;
}

public int getOwnerId() {

return ownerId;
}

public void setOwnerId(int ownerId) {

this.ownerId = ownerId;
}

public List<Integer> getEmployeeIds() {

return employeeIds;
}

public void setEmployeeIds(List<Integer> employeeIds) {

this.employeeIds = employeeIds;
}

public void addEmployee(int id) {
this.employeeIds.add(id);
}

public void removeEmployee(int id) {
this.employeeIds.remove(new Integer(id));
}
}

如您所见,我添加了两个方法,它们并不直接是 getter 和 setter,但它们就像方便的方法,可以轻松访问集合并添加/删除员工。

当我在程序中调用“addEmployee()”时,我收到一个简单的 NullPointerException。问题基本上是如何将集合初始化为不具有null,因为我读到Hibernate使用集合的内部实现,而不是简单地采用ArrayList.

感谢您提前提供帮助。

最佳答案

你有一个NullPointerException,因为你必须自己初始化列表。您使用哪种实现并不重要。这将解决您的问题:

@ElementCollection
@Column(name = "employee")
private List<Integer> employeeIds = new ArrayList<>();

关于java - 在 Hibernate 中添加 Employee 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25552744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com