在JPA实体关系中获取错误的简单示例

时间:2016-07-07 05:00:58

标签: java mysql spring hibernate jpa

我正在使用注释在spring中执行简单的JPA实体关系,而我收到错误“ com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Column'id'不能为null “; 下面是我的pojos

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;
    }

}

那么可以解决这个问题呢?

2 个答案:

答案 0 :(得分: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;

}

答案 1 :(得分:0)

请检查以下内容:

数据库中定义了名为STUDENTDB的表,主键列id具有AUTO_INCREMENT属性。

如果没有上述属性@GeneratedValue(strategy = GenerationType.AUTO),则无法在当前方案中使用。