开发者社区> 问答> 正文

使用@OneToMany进行级联保存时,出现Many端没法保存One端的ID而出现报错?报错

create table student
(
    id bigint auto_increment primary key,
    name varchar(30) default '' not null,
    age int default '0' not null,
    school_id bigint default '0' not null
)
comment '学生';

create table school
(
    id bigint auto_increment primary key,
    name varchar(30) default '' not null
) comment '学校';

实体类:

@Data
@Entity
@Accessors(chain = true)
public class School {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;
    private String name;

    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "school")
    private List<Student> students = new ArrayList<>();

    public School addStudent(Student student) {
        students.add(student);
        return this;
    }
}

@Data
@Entity
@Accessors(chain = true)
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Integer age;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "school_id")
    private School school;
}

具体操作:

School school = new School();
school.setName("学校");
Student student1 = new Student();
student1.setName("张三").setAge(18);
Student student2 = new Student();
student2.setName("李四").setAge(19);

school.addStudent(student1).addStudent(student2);
schoolRepository.save(school);

通过以上的操作,由于student表里的school_id设置了not null ,执行以上操作时报错Column 'school_id' cannot be null;

还尝试了在数据库里student里设置了school_id字段为外键,结果还是不行;

请问有遇到过这种问题的么?

 

 

展开
收起
爱吃鱼的程序员 2020-06-06 15:47:48 1014 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
                        <p>少了student1.setSchool() 这个操作吧。</p>
    
                    
    
                            我试过了,会导致StackOverflowError,嵌套循环了
                        
    
                                回复 <a class="referer" target="_blank">@Janyd</a>  : 你把student放到了school,但是student里面的school还是NULL呀
                        
    
                            我是将两个student放到school里的 然后新增school的
    
                        
    
                        <p>请问你这个问题后来有解决么.我也遇到了</p>
    
    2020-06-06 15:48:00
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
事务、全局索引、透明分布式 立即下载
面向失败设计 立即下载
低代码开发师(初级)实战教程 立即下载