Jpa associated non-primary key column, failed to save data

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.

Apr.09,2021

there is a problem with the configuration of ManyToOne. Modify it as follows:

public class Student{
    @Id
    private String id;
    
    @Size(max = 20)
    private String code;
    
    @Size(max = 200)
    private String name;
    
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name="classCode")
    private Class class;
    ...
}

my local test passed, and the test environment is:

  • Spring Boot 2.0.4.RELEASE
  • Hibernate JPA 2.1
  • Hibernate 5.2.17
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1be86d2-30c54.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1be86d2-30c54.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?