2014-08-28 60 views
0

增加僱員時,我有其中有這段代碼Hibernate的實體「內聯網」:的NullPointerException在Hibernate中

// 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

感謝您的幫助。

+0

在'addEmployee()'之前調用'setEmployeeIds()'。 – 2014-08-28 15:39:24

回答

2

你有一個NullPointerException,因爲你必須自己初始化列表。使用哪種實現無關緊要。這將解決您的問題:

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

很酷,謝謝。那麼關於Hibernate的內部實現的不同於ArrayList和其他的信息是錯誤的?或者Hibernate是否將其設置爲實現? – MrPixelDream 2014-08-28 17:00:37

+0

嗯,我不知道你在哪裏讀過,但我不認爲Hibernate需要任何List實現。我的意思是隻要我們提供實現List的東西,hibernate就會使用這個接口中的函數。無論它在界面背後究竟是什麼。 – Zakor 2014-08-28 19:48:09

相關問題