如何仅从关系中检索属性而不是实体?

我正在 Netbeans 中开发一个 Maven Web 应用程序项目,我有以下类:


@Entity

@Table(name = "departments")

public class Department{

    @Id

    private Integer departmentId;

    @Column(name = "department_name")

    private String departmentName;

}

和:


@Entity

@Table(name = "employees")

public class Employee {

    @Id

    private Integer employeetId;

    @Column(name = "employee_name")

    private String employeeName;

    @JoinColumn(name = "department_id", referencedColumnName = 

    "department_id")

    @ManyToOne(optional = false)

    private Departments department;

}

我的休息 api 返回这个:


{

    employeeId:1, 

    employeeName:"Jhon",

    department: { departmentId:1, departmentName:"IT"}

}

我想要的输出是:


 {

    employeeId:1, 

    employeeName:"Jhon",

    department: "IT"

 }

我尝试返回一个 DTO,但得到一个空的 json:


@GET

@Produces(MediaType.APPLICATION_JSON)

public List<EmployeeDto> findAllEmployees() {

    CriteriaQuery cq = entityManager.getCriteriaBuilder().createQuery(Employee.class);

    cq.select(cq.from(Employee.class));

    List<Employee> employees = entityManager.createQuery(cq).getResultList();

    List<EmployeeDto> employeesDto = new ArrayList<>();


    for (Employee employee : employees) {

        EmployeeDto employeeDto = new EmployeeDto();

        employeeDto.employeeId = employee.getEmployeedId();

        employeeDto.department = employee.getDepartment().getDepartmentName();


        employeesDto.add(employeeDto);

    }

    return   employeesDto;

DTO:


Class EmployeeDto{Integer employeeId; String employeeName; String department}


米琪卡哇伊
浏览 130回答 2
2回答

万千封印

这是因为我得到了一个空的 json:我的 Dto 类没有公共 getter 和 setter。解决方案是公开 Dto 字段或添加公共 getter/setter。Class EmployeeDto{&nbsp; &nbsp; public Integer employeeId;&nbsp;&nbsp; &nbsp; public String employeeName;&nbsp;&nbsp; &nbsp; public String department;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java