表
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字段为外键,结果还是不行;
请问有遇到过这种问题的么?
<p>少了student1.setSchool() 这个操作吧。</p>
我试过了,会导致StackOverflowError,嵌套循环了
回复 <a class="referer" target="_blank">@Janyd</a> : 你把student放到了school,但是student里面的school还是NULL呀
我是将两个student放到school里的 然后新增school的
<p>请问你这个问题后来有解决么.我也遇到了</p>
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。