for example,
class table (class_id primary key, class_code is unique)
class_id,class_code,class_name
student table (stu_id primary key, class_code is the class_code of class table)
stu_id,stu_code,stu_name,class_code
the class_code of the student table is associated with
through ManyToOne. The code is as follows, with part of the code omitted
public class Class{
@Id
private String id;
@Size(max = 20)
@Column(unique = true)
private String code;
@Size(max = 200)
private String name;
...
}
public class Student{
@Id
private String id;
@Size(max = 20)
private String code;
@Size(max = 200)
private String name;
@ManyToOne
@JoinColumn(name="classCode",referencedColumnName="code")
private Class class;
...
}
there is now an student data insert operation
@Autowired
private StudentRepository stuRepository;
Student stu = new Student();
Class class = new Class();
class.setCode("class_code");
stu.setClass(class);//code
...
stuRepository.save(stu);
before, there was no problem with the primary key ID associated with class, but it is not possible to associate with non-primary key code, to save data. Is it because it is necessary to associate with primary key? I think there are many related non-primary keys on the Internet, indicating that it is possible to do so, but you do not know what is wrong.