如何将 DTO 转换为具有相关列的实体

How to convert DTO to an entity with a related column

这可能是对我昨天在这里的问题的重复 Can't save data to a database with DTO 我可以作为 DTO 收到请求。但后来我将其转换为模型 class 回来,我将 regionid 列的值为 null。

我的 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;
}

我的模特:

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;
    }
    
    
    
}

控制器:

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);
      }
    }
}

尝试将 id 设置为实体。

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

    

使用ModelMapper。 如果您的实体 class id 字段使用 @Id 注释和自动生成的 JPA 密钥,例如 @GeneratedValue(strategy = GenerationType.IDENTITY) 作为 id,那么仅使用模型映射器并保存实体应该会给您预期的结果。
否则,如果手动设置 PKID 值然后保存实体。

更新:对于您更新后的问题, 在您的 Towns 实体中添加整个区域:

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