0

This is probebly a repetition to my yesturday's question here Can't save data to a database with DTO I can get a request as DTO. But then I convert it to a model class back I get value of regionid column as null.

My DTO Class

package com.example.dto;
import java.util.HashSet;
import java.util.Set;

import lombok.Data;

@Data
public class TownDTO {
    public String name;
       public String regionid;
}

My model:

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import com.fasterxml.jackson.annotation.JsonIgnore;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "towns")

public class Towns {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(name = "name")
    private String name;
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
        @JoinColumn(name = "regionid", nullable = false)
        @OnDelete(action = OnDeleteAction.CASCADE)
        private Regions regionid;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Regions getRegionid() {
        return regionid;
    }
    public void setRegionid(Regions regionid) {
        this.regionid = regionid;
    }
    
    
    
}

Controller:

package com.example.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.dto.TownDTO;
import com.example.model.Regions;
import com.example.model.Towns;
import com.example.repository.TownsRepository;
import com.example.repository.RegionsRepository;
import java.util.stream.Collectors;

import org.modelmapper.Conditions;
import org.modelmapper.ModelMapper;

@CrossOrigin(origins = "http://localhost:8081")

@RestController
@RequestMapping("/towns")

public class TownsController {

    @Autowired
    TownsRepository townsrepository;
    @Autowired
    RegionsRepository regionsrepository;
    @Autowired
    private ModelMapper modelMapper;
    
    @GetMapping("/list")
    public ResponseEntity<List<Towns>> getAllTowns(@RequestParam(required = false) String name) {
      try {
        List<Towns> towns = new ArrayList<Towns>();

        if (name == null)
          townsrepository.findAll().forEach(towns::add);
        else
          townsrepository.findByNameContaining(name).forEach(towns::add);

        if (towns.isEmpty()) {
          return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }

        return new ResponseEntity<>(towns, HttpStatus.OK);
      } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
    
    @GetMapping("/list/{id}")
    public ResponseEntity<Towns> getTownById(@PathVariable("id") int id) {
      Optional<Towns> townData = townsrepository.findById(id);

      if (townData.isPresent()) {
        return new ResponseEntity<>(townData.get(), HttpStatus.OK);
      } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
      }
    }

    @PostMapping("/add")
    public ResponseEntity<TownDTO> createPost(@RequestBody TownDTO townDto) {

        
        // convert DTO to entity
    
        Towns townRequest = modelMapper.map(townDto, Towns.class);
        System.out.println("reg");  
        System.out.println(townRequest.getName());
        System.out.println(townRequest.getRegionid());
        //Regions rid=regionsrepository.findById(2).get();
    //  townRequest.setRegionid(townDto.regionid);
        Towns town = townsrepository.save(townRequest);
        
        // convert entity to DTO
        TownDTO townResponse = modelMapper.map(town, TownDTO.class);

        return new ResponseEntity<TownDTO>(townResponse, HttpStatus.CREATED);
    }
    /*
    @PostMapping("/addt")
    
    public ResponseEntity<Towns> createtown2(@RequestBody Towns town) {
      try {
            
          Towns _town = townsrepository
            .save(town);
         // Towns _town = townsrepository .save(new Towns( town.getName(), regionsrepository.findByRegionId(town.getRegionid())));
          return new ResponseEntity<>(_town, HttpStatus.CREATED);
      } catch (Exception e) {
       System.out.println(e.getMessage());
        System.out.println("region");
        System.out.println(town.getRegionid());
    
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
    */
    @PutMapping("/edit/{id}")
    /*
    public ResponseEntity<Towns> updateTown(@PathVariable("id") int id, @RequestBody Towns town) {
      Optional<Towns> townData = townsrepository.findById(id);

      if (townData.isPresent()) {
        Towns _town = townData.get();
        _town.setName(town.getName());
        _town.setRegionid(town.getRegionid());
        return new ResponseEntity<>(townsrepository.save(_town), HttpStatus.OK);
      } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
      }
    }
    */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<HttpStatus> deleteTown(@PathVariable("id") int id) {
      try {
        townsrepository.deleteById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
      } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
}

Try to set id to an entety.

Regions rgid=regionsrepository.findById(2).get();
        townRequest.setRegionid(rgid.getId());

    
Bogdan Onyshenko
  • 415
  • 1
  • 6
  • 24

1 Answers1

3

use ModelMapper. If your entity class id field uses @Id annotation with auto-generating JPA key like @GeneratedValue(strategy = GenerationType.IDENTITY) as id, then using only model mapper and saving the entity should give you the expected result.
Otherwise, if set your PKID value manually and then save the entity.

Update: for your updated question, add the whole Region in your Towns entity:

Regions rgid=regionsrepository.findById(2).get();
townRequest.setRegionid(rgid);
user404
  • 1,934
  • 1
  • 16
  • 32
  • I have updated the question. Added entity DTO and a controller class. ModelMapper is probably greate if it was working )). – Bogdan Onyshenko Jan 11 '22 at 09:30
  • Did you check the link I provided? Your region name is in String in dto, but not in entity class. Though it should omit while using modelmapper and should work fine. In `@PostMapping("/add")` API, you are saving Region, not the `Town` entity – user404 Jan 11 '22 at 10:13
  • Oh no... Previously I have posted a wrong controller. Edited the question. Sorry for that. About the entity, shouldn't it be that relatedid column must be in a type of model? – Bogdan Onyshenko Jan 11 '22 at 10:25
  • you can send only the regionId but before saving it, you need to fetch the region related to that regionId and then set that to your town entity before saving it. This will work. – user404 Jan 11 '22 at 10:27
  • If you think, you will send the whole entity of regionId in town dto, you can do it too. Just change the type of regionId from Long to Regions[your entity name] – user404 Jan 11 '22 at 10:39
  • The method setRegionid(Regions) in the type Towns is not applicable for the arguments (int) That is after I try to set id from regions repository. Will add it in a question. – Bogdan Onyshenko Jan 11 '22 at 10:58
  • Changed the question. Added fetching id before saving. – Bogdan Onyshenko Jan 11 '22 at 11:01
  • check the updated ans – user404 Jan 11 '22 at 11:15