0

i am doing a rest application and i have problems when i use @PostMaping I have 2 classes with models of the first TblEmployees and 2 classes of TblDepartments they are connected on foreign key = "dbID"

when i insert:

 {
     "empName": "days",
     "empActive": 0,
     "dbID": 15,
     "dep_name": "sso"
 }

gives an error SQL Error: 1452

here is my code:

TblEmployees має поля empName, empActive,dbID
TblEmployees має поля dbID, dep_name
EmployessServise

    public TblEmployees add_Employees(TblEmployees tblEmployees){
    return  repo.save(tblEmployees);

EmployesController

@PostMapping("/add_Emp")
public TblEmployees add_emp(@RequestBody TblEmployees tblEmployees){
    return  service.add_Employees(tblEmployees);

@Entity
@Table(name = "employees")
public class TblEmployees {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int emp_id;
    private String empName;
    private Boolean empActive;
    private Integer dbID;
    @ManyToOne
    @JoinColumn(name = "dbid",insertable = false,updatable = false)
    private TblDepartments departments;
---getter setter

@Entity
@Table(name = "departments")
public class TblDepartments {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "dbID")
    private Integer dbID;
    private String dep_name;


    public TblDepartments(){
    }

---getter setter
Nora Na
  • 162
  • 1
  • 16
robot
  • 19
  • 4
  • I assume that you're using MySQL database, then the error code 1452 means *Cannot add or update a child row: a foreign key constraint fails*. So please make sure that `dbID` does EXISTS in another table. – LHCHIN Nov 03 '21 at 09:55
  • dbID are in both tables – robot Nov 03 '21 at 10:43

1 Answers1

0

You SQL Error code shows that the foreign key you are sending in you request body (which is dbID) does not exist in the departments table.

Double check you departments table. Make sure you are sending the correct foreign key (dbId-One that exists in table of departments). You can find more info on the error here

Nora Na
  • 162
  • 1
  • 16