Home > Mobile >  json object returns null spring boot
json object returns null spring boot

Time:11-02

І am developing a REST API app with Spring Boot. I have 2 tables in the database, the first is called TblEmployees, the second is called TblDepartments. From these 2 tables I made a class Employees_DTO which should return data in JSON format. And from the TblEmployees table it will return data and from the TblDepartments table it returns null. dbID is a foreign key I did as I thought but at me it doesn't work:

    public class TblDepartments {
private Integer dbID;
private String dep_name;

public class TblEmployees {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int emp_id;
private String empName;
private Boolean empActive;
private Integer dbID;

public class Employees_DTO {
private int emp_id;
private String empName;
private Boolean empActive;
private String dep_name;
   }

package com.example.test_task.exceptions;

import com.example.test_task.*;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.modelmapper.spi.MatchingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
 import java.util.stream.Collectors;

 @Service
public class EmployessServise {
@Autowired
private EmplployeesRepository repo;

@Autowired
private ModelMapper modelMapper;

public EmployessServise() {
}

public List<Employees_DTO> getAll_Emp(){
    return repo.findAll()
            .stream()
            .map(this::convertEntityToDto)
            .collect(Collectors.toList());
}

private Employees_DTO convertEntityToDto(TblEmployees tblEmployees){
    modelMapper.getConfiguration()
            .setMatchingStrategy(MatchingStrategies.LOOSE);
    Employees_DTO employees_dto=new Employees_DTO();
    employees_dto=modelMapper.map(tblEmployees,Employees_DTO.class);
    return employees_dto;
}

private TblEmployees convertEntityToDto(Employees_DTO employees_dto){
    modelMapper.getConfiguration()
            .setMatchingStrategy(MatchingStrategies.LOOSE);
    TblEmployees tblEmployees=new TblEmployees();
    tblEmployees=modelMapper.map(employees_dto,TblEmployees.class);
    return tblEmployees;
}
  }

CodePudding user response:

@ManyToOne is available:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class TblEmployees {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int emp_id;
    private String empName;
    private Boolean empActive;
    @ManyToOne
    @JoinColumn(name = "dbid")
    private TblDepartments department;

    // Getters and Setters

}

full sample code

  • Related