2016-07-07 43 views
0

我正在做很簡單的JPA實體關係,很多在春天使用註釋,而我收到錯誤,「com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'id'不能爲空「; 下面是我的POJO在JPA實體關係中出現錯誤簡單示例

import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.Table; 

@Entity 
@Table(name = "STUDENTDB") 
public class Student { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long id; 
    private String name; 

    public long getId() { 
     return id; 
    } 

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

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 

,並映射類爲如下。

import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.JoinColumn; 
import javax.persistence.ManyToOne; 

@Entity 
public class Marks { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private long sid; 
    private int subject1; 
    private int subject2; 
    private int subject3; 

    @ManyToOne(optional=false) 
    @JoinColumn(name="id",referencedColumnName="id") 
    private Student s; 

    public Student getS() { 
     return s; 
    } 

    public void setS(Student s) { 
     this.s = s; 
    } 

    public long getSid() { 
     return sid; 
    } 

    public void setSid(long sid) { 
     this.sid = sid; 
    } 

    public int getSubject1() { 
     return subject1; 
    } 

    public void setSubject1(int subject1) { 
     this.subject1 = subject1; 
    } 

    public int getSubject2() { 
     return subject2; 
    } 

    public void setSubject2(int subject2) { 
     this.subject2 = subject2; 
    } 

    public int getSubject3() { 
     return subject3; 
    } 

    public void setSubject3(int subject3) { 
     this.subject3 = subject3; 
    } 

} 

那麼有什麼可能的解決方案呢?

+0

也許'@Column(name =「ID」,獨特= TRUE,可爲空= FALSE)' –

+0

你怎麼調用這些類,共享代碼的那部分,並導致該異常 –

+0

當語句在保存「學生」或「標記」的同時是否獲得了「例外」? –

回答

0

請檢查以下內容:

命名STUDENTDB表在數據庫中被定義爲使得主鍵列id具有AUTO_INCREMENT屬性。

沒有上述屬性@GeneratedValue(strategy = GenerationType.AUTO)是不會在目前的情況下工作。

1
package com.example; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.Table; 

@Entity 
@Table(name = "STUDENTDB") 
public class Student { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(nullable=false,updatable=false) 
    private long id; 
    private String name; 

}