Home > front end >  How to implement @ForeignKey correctly using Spring Boot
How to implement @ForeignKey correctly using Spring Boot

Time:09-03

I am developing my first application using Spring Boot to build my web service. The application is supposed to be a simple gym management system. Actually I managed to create model, controller and repository for Admin (gym owner entity) and Palestra (gym entity).

Admin.java

@Entity(name="admin")
public class Admin {
    private @Id @GeneratedValue Long id_admin;
    private String nome;
    private String cognome;
    private String email;
    private String password;
    
    // Retionships
    @OneToMany(mappedBy="admin", fetch = FetchType.LAZY)
    private List <Palestra> palestre;
    
    Admin() {} // Empty constructor

    public Admin(Long id_admin, String nome, String cognome, String email, String password) {
        super();
        this.nome = nome;
        this.cognome = cognome;
        this.email = email;
        this.password = password;
    }

    public Long getId_admin() {
        return id_admin;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCognome() {
        return cognome;
    }

    public void setCognome(String cognome) {
        this.cognome = cognome;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Palestra> getPalestre() {
        return palestre;
    }

    public void setPalestre(List<Palestra> palestre) {
        this.palestre = palestre;
    }
    
}

AdminController.java

@RestController
public class AdminController {
    private final AdminRepository adminRepository;
    
    public AdminController(AdminRepository repository) {
        adminRepository = repository;
    }
    
    @GetMapping("/admins")
    Iterable<Admin> getAdmins() {
        return adminRepository.findAll();
    }
    
    @PostMapping("/admins")
    Admin createAdmin(@RequestBody Admin newAdmin) {
        return adminRepository.save(newAdmin);
    }
}

Palestra.java

@Entity(name="palestra")
public class Palestra {
    private @Id @GeneratedValue Long id_palestra;
    private String nome;
    private String via;
    private int civico;
    private String citta;
    
    // Relationships
    @OneToMany(mappedBy="palestra")
    private List<Trainer> trainers;
    
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="id_admin")
    private Admin admin;
    
    public Palestra() {} // Empty constructor

    public Palestra(Long id_palestra, String nome, String via, int civico, String citta) {
        super();
        this.id_palestra = id_palestra;
        this.nome = nome;
        this.via = via;
        this.civico = civico;
        this.citta = citta;
    }

    public Long getId_palestra() {
        return id_palestra;
    }

    public void setId_palestra(Long id_palestra) {
        this.id_palestra = id_palestra;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getVia() {
        return via;
    }

    public void setVia(String via) {
        this.via = via;
    }

    public int getCivico() {
        return civico;
    }

    public void setCivico(int civico) {
        this.civico = civico;
    }

    public String getCitta() {
        return citta;
    }

    public void setCitta(String citta) {
        this.citta = citta;
    }

    public Admin getAdmin() {
        return admin;
    }

    public void setAdmin(Admin admin) {
        this.admin = admin;
    }

}

PalestraController.java

@RestController
public class PalestraController {
    private final PalestraRepository palestraRepository;
    
    public PalestraController(PalestraRepository repository) {
        palestraRepository = repository;
    }
    
    @GetMapping("/palestre")
    Iterable<Palestra> getPalestre() {
        return palestraRepository.findAll();
    }
    
    @PostMapping("/palestre")
    Palestra createPalestra(@RequestBody Palestra newPalestra) {
        return palestraRepository.save(newPalestra);
    }
}

I used Postman to send and test requests: enter image description hereenter image description here and this is the result stored in the database: enter image description here

As you can see id_admin is supposed to be foreign key but has a NULL value. How I can solve this problem?

CodePudding user response:

you'll have to link the entities...

@PostMapping("/admins")
@Transactional
Admin createAdmin(@RequestBody Admin newAdmin) {
  //find palestra by id
  Palestra p = palestraRepo.findById(newAdmin.id_palestra);
  Admin storedAdmin = adminRepository.save(newAdmin);
  //link with admin
  p.setAdmin(storedAdmin);
  palestraRepo.save(p)
  return storedAdmin;
}

CodePudding user response:

I answer my own question because I found the problem. In the way I created models, controllers and repositories the entities were already linked by the relationship (@ManyToOne and @OneToMany). The real "problem" was how the request was submitted through Postman. I had to insert in my request the admin_id value manually like this: enter image description here

  • Related