我有一个Hibernate Entity" 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的方法,但他们喜欢方便的方法来轻松访问该集合并添加/删除员工。
当我打电话给&#34; addEmployee()&#34;在我的程序中,我得到一个简单的NullPointerException。问题基本上是我如何初始化集合而没有null
,因为我读到Hibernate使用集合的内部实现而不仅仅是ArrayList
。
提前感谢您的帮助。
答案 0 :(得分:2)
您有一个NullPointerException
,因为您必须自己初始化列表。使用哪种实现并不重要。这将解决您的问题:
@ElementCollection
@Column(name = "employee")
private List<Integer> employeeIds = new ArrayList<>();