【问题标题】:sql constraint violation exceptionsql约束违反异常
【发布时间】:2021-12-05 00:53:10
【问题描述】:

我有一个由 MathematicsAnswer 引用的实体数学。如果对数学执行发布请求,我会得到 MathsAnswer 上的字段不能为空的异常。但我实际上确实在场上进行了级联。请我需要解决这个问题。 java.sql.SQLIntegrityConstraintViolationException: Column 'question_id' cannot be null

sql 架构:

CREATE TABLE MATHEMATICS(
id integer not null auto_increment,
year date not null,
question_no int not null,
question varchar(128) default null,
primary key(id)
) engine=InnoDb;

CREATE TABLE MATHS_ANSWER(
id integer not null auto_increment,
date date default null,
question_no int not null,
question_id int not null,
solution varchar(128) default null,
solution_url varchar(128) default null,
primary key(id),
foreign key(question_id) references MATHEMATICS(id) ON DELETE NO ACTION ON UPDATE NO ACTION
) engine = InnoDb;

实体类:

@Entity
        @Table(name = "Mathematics")
        public class Mathematics {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Integer id;
    
    @Column(name = "year")
    private Date year;
    
    @Column(name = "question_no")
    private Integer questionNo;
    
    @Column(name = "question")
    private String question;
    
    @OneToOne(mappedBy = "maths", fetch = FetchType.EAGER,cascade = CascadeType.ALL
            )
    private MathsAnswers answers = new MathsAnswers();//getters & setters

MathsAnswers.java:

 @Entity
            @Table(name = "Mathematics")
            public class Mathematics {
    
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.SEQUENCE)
        private Integer id;
        
        @Column(name = "year")
        private Date year;
        
        @Column(name = "question_no")
        private Integer questionNo;
        
        @Column(name = "question")
        private String question;
        
        @OneToOne(mappedBy = "maths", fetch = FetchType.EAGER,cascade = CascadeType.ALL
                )
        private MathsAnswers answers = new MathsAnswers();//getters & setters
            

jpaRepo:

@RepositoryRestResource(collectionResourceRel = "mathematics", path = "maths")
public interface MathsRepo extends JpaRepository<Mathematics, Integer> {

}

发布请求:

{
    "year":"2004-01-03",
    "questionNo":"4",
    "question":"How many weeks makes a year?"
}

【问题讨论】:

  • 您在问题中添加了两次相同的实体而不是 MathAnswers.java。

标签: java mysql hibernate spring-data-jpa


【解决方案1】:

为我的MathsAnswer 实体指定的表名错误;应该是 Mathsanswer 而不是 Mathematics

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2014-10-08
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    相关资源
    最近更新 更多