Home > front end >  When I add an Entity with hibernate the foreign key is not saved always an null
When I add an Entity with hibernate the foreign key is not saved always an null

Time:04-14

I have two classes Panier.java and Categorie.java with OneToMany relationship. When I post via postman a panier with category id, all the data are stored correctly except the category in the DB and the foreign key in the panier table is stored always as null.

Panier.java

package com.app.saveeat.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;

@Entity
@AllArgsConstructor
public class Panier implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String nom;
    private String description;
    private Double prixInitial;
    private Double prixOffre;
    private String quantity;
    private LocalDateTime dateDebut;
    private LocalDateTime dateFin;
    private String image;
    private String adresse;
    @Column(nullable = false,updatable = false)
    private String codePanier;



    @JsonIgnore
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn (name = "categorie")
    private Categorie categorie;

    public Panier(){}
    public Panier(String nom, String description, Double prixInitial, Double prixOffre, String quantity, LocalDateTime dateDebut,LocalDateTime dateFin, String image, String adresse, String codePanier){
        this.nom = nom;
        this.description = description;
        this.prixInitial = prixInitial;
        this.prixOffre = prixOffre;
        this.quantity = quantity;
        this.dateDebut = dateDebut;
        this.image = image;
        this.adresse = adresse;
        this.codePanier = codePanier;
        this.dateFin = dateFin;
    }

    public Long getId(){
        return id;
    }

    public void setId(Long id){
        this.id = id;
    }

    public String getNom(){
        return nom;
    }

    public void setNom(String nom){
        this.nom = nom;
    }

    public String getDescription(){
        return description;
    }

    public void setDescription(String description){
        this.description = description;
    }

    public Double getPrixInitial(){
        return prixInitial;
    }

    public void setPrixInitial(Double prixInitial){
        this.prixInitial = prixInitial;
    }

    public Double getPrixOffre(){
        return prixOffre;
    }

    public void setPrixOffre(Double prixOffre){
        this.prixOffre = prixOffre;
    }

    public String getQuantity(){
        return quantity;
    }

    public void setQuantity(String quantity){
        this.quantity = quantity;
    }

    public LocalDateTime getDateDebut(){
        return dateDebut;
    }

    public void setDateDebut(LocalDateTime dateDebut){
        this.dateDebut = dateDebut;
    }

    public LocalDateTime getDateFin() { return dateFin; }

    public void setDateFin(LocalDateTime dateFin) {
        this.dateFin = dateFin;
    }

    public String getImage(){
        return image;
    }

    public void setImage(String image){
        this.image = image;
    }

    public String getAdresse(){
        return adresse;
    }

    public void setAdresse(String adresse){
        this.adresse = adresse;
    }

    public String getCodePanier(){
        return codePanier;
    }

    public void setCodePanier(String codePanier){
        this.codePanier = codePanier;
    }

    public Categorie getCategorie() {
        return categorie;
    }

    public void setCategorie(Categorie categorie) {
        this.categorie = categorie;
    }

    @Override
    public String toString(){
        return "Panier{"  
                "id="   id  
                ", nom='"   nom   '\''  
                ", description='"   description   '\''  
                ", prixInitial='"   prixInitial   '\''  
                ", prixOffre='"   prixOffre   '\''  
                ", quantity='"   quantity   '\''  
                ", dateDebut='"   dateDebut   '\''  
                ", dateFin='"   dateFin   '\''  
                ", image='"   image   '\''  
                ", adresse='"   adresse   '\''  
                ", categorie='"   categorie   '\''  
                '}';
    }
}

Categorie.java

package com.app.saveeat.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


@Entity
@Data
@AllArgsConstructor
public class Categorie implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, updatable = false)
    private Long id;
    private String nom;

    @JsonIgnore
    @OneToMany(mappedBy = "categorie",cascade = CascadeType.ALL)
    private List<Panier> paniers;

    public List<Panier> getPaniers() {
        return paniers;
    }

    public void setPaniers(List<Panier> paniers) {
        this.paniers = paniers;
    }

    public Categorie() {}
    public Categorie(Long id, String nom) {
        this.id = id;
        this.nom = nom;
    }



    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }
}

PanierController.java

package com.app.saveeat.controller;

import com.app.saveeat.entity.Categorie;
import com.app.saveeat.entity.Panier;
import com.app.saveeat.service.PanierService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "/panier",
        headers = "Accept=application/json",
        method = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE })
public class PanierController {
    private final PanierService panierService;

    public PanierController(PanierService panierService) {
        this.panierService = panierService;
    }

    @GetMapping("/all")
    public ResponseEntity<List<Panier>> getAllPaniers(){
        List<Panier> paniers = panierService.findAllPaniers();
        return new ResponseEntity<>(paniers, HttpStatus.OK);
    }

    @GetMapping("/find/{id}")
    public ResponseEntity<Panier> getPanierById(@PathVariable("id") Long id){
        Panier panier = panierService.findPanierById(id);
        return new ResponseEntity<>(panier, HttpStatus.OK);
    }

    @PostMapping("/add")
    public ResponseEntity<Panier> addPanier(@RequestBody Panier panier){
        Panier newPanier = panierService.addPanier(panier);
        return new ResponseEntity<>(newPanier, HttpStatus.CREATED);
    }

    @PutMapping("/update")
    public ResponseEntity<Panier> updatePanier(@RequestBody Panier panier){
        Panier updatePanier = panierService.updatePanier(panier);
        return new ResponseEntity<>(updatePanier, HttpStatus.OK);
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deletePanier(@PathVariable(value = "id") Long id){
        panierService.deletePanier(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }


}

CategorieController.java

package com.app.saveeat.controller;

import com.app.saveeat.entity.Categorie;
import com.app.saveeat.service.CategorieService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

    @CrossOrigin(origins = "*")
    @RestController
    @RequestMapping(value = "/categorie")
    public class CategorieController {
    private final CategorieService categorieService;
    public CategorieController(CategorieService categorieService) {
        this.categorieService = categorieService;
    }

    @GetMapping("/all")
    public ResponseEntity<List<Categorie>> getAllCategories(){
        List<Categorie> categories = categorieService.findAllCategories();
        return new ResponseEntity<>(categories, HttpStatus.OK);
    }

    @GetMapping("/find/{id}")
    public ResponseEntity<Categorie> getCategorieById(@PathVariable("id") Long id){
        Categorie categorie = categorieService.findCategorieById(id);
        return new ResponseEntity<>(categorie, HttpStatus.OK);
    }
}



PanierService.java

package com.app.saveeat.service;

import com.app.saveeat.entity.Panier;
import com.app.saveeat.exception.PanierNotFoundException;
import com.app.saveeat.repository.PanierRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class PanierService {
    private final PanierRepository panierRepository;

    @Autowired
    public PanierService(PanierRepository panierRepository) {
        this.panierRepository = panierRepository;
    }

    public Panier addPanier(Panier panier){
        panier.setCodePanier(UUID.randomUUID().toString());
        return panierRepository.save(panier);
    }

    public List<Panier> findAllPaniers(){
        return panierRepository.findAll();
    }

    public Panier updatePanier(Panier panier){
        return panierRepository.save(panier);
    }

    public Panier findPanierById(Long id){
        return  panierRepository.findPanierById(id).orElseThrow(() -> new PanierNotFoundException("Panier by id"   id   "was not found"));
    }

    public void deletePanier(Long id){
        panierRepository.deletePanierById(id);
    }
}



CategorieService.java

package com.app.saveeat.service;

import com.app.saveeat.entity.Categorie;
import com.app.saveeat.exception.CategorieNotFoundException;
import com.app.saveeat.repository.CategorieRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class CategorieService {
    private final CategorieRepository categorieRepository;

    @Autowired
    public CategorieService(CategorieRepository categorieRepository) {
        this.categorieRepository = categorieRepository;
    }

    public List<Categorie> findAllCategories(){
        return categorieRepository.findAll();
    }
    public Categorie findCategorieById(Long id){
        return  categorieRepository.findCategorieById(id).orElseThrow(() -> new CategorieNotFoundException("Categorie by id"   id   "was not found"));
    }
}

postman api test Request

{
    "nom": "panier1 ",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
    "prixInitial": 11,
    "prixOffre":10,
    "quantity": "12",
    "dateDebut": "2022-03-30T19:00:00.000Z",
    "dateFin": "2022-03-30T21:30:15.000Z",
    "image": "https://bootdey.com/img/Content/avatar/avatar4.png",
    "adresse": "France",
    "codePanier": "4570090332",
    "categorie": {
        "id": 2
    }
}

Response

{
    "nom": "panier1 ",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
    "prixInitial": 11,
    "prixOffre":10,
    "quantity": "12",
    "dateDebut": "2022-03-30T19:00:00.000Z",
    "dateFin": "2022-03-30T21:30:15.000Z",
    "image": "https://bootdey.com/img/Content/avatar/avatar4.png",
    "adresse": "France",
    "codePanier": "f4466839-c498-4c2a-b1de-48c184aed450"
}
any help please ?

CodePudding user response:

Your problem is that you never link the objects before persisting them. Below is one way that should fix it:

@Service
@Transactional
public class PanierService {
    private final PanierRepository panierRepository;
    private final CategoryRepository categoryRepository;

    @Autowired
    public PanierService(PanierRepository panierRepository, CategoryRepository categoryRepository) {
        this.panierRepository = panierRepository;
        this.categoryRepository = categoryRepository;
    }

    public Panier addPanier(Panier panier){
        Category category = categoryRepository.findById(panier.getCategory().getId()).orElseThrow();
        panier.setCategory(category);
        panier.setCodePanier(UUID.randomUUID().toString());
        return panierRepository.save(panier);
    }

    // ...other methods
}

CodePudding user response:

@JsonIgnore
@OneToMany(mappedBy = "categorie",cascade = CascadeType.ALL)
private ArrayList<Panier> paniers = new ArrayList<>();

this might fix the NPE

  • Related