EclipseLink 的所有属性都显示为 JSON

EclipseLink all attributes are displayed as JSON

我在实体中有以下 JPQL class

select new test.entity.Emp(o.empNo, o.empName) from Emp o

在服务层

@GET
@Path("/results")
@Produces(MediaType.APPLICATION_JSON)
public List<Emp> findAll() {
    Query query =             getEntityManager().createNamedQuery("Emp.findAll");
    List<Emp> result = query.getResultList();
    return result;
}

然而,当我 运行 时,所有属性都显示在 JSON 结果中,而不是 empNoEmpName

可能是什么原因?

您的查询 returns 个新的 Emp 对象(仅由 empNo 和 empName 构造),因此这将是您的 JSON 字符串的结果 - 整个 Emp 对象。

像这样创建 class:

public class EmpDTO {
    private String empNo; //or whatever datatype you use...
    private String empName;

    public EmpDTO(String empNo, String empName) {
        this.empNo = empNo;
        this.empName = empName;
    }

    //getters and setters
}

然后编辑您的查询以在构造函数表达式中使用此 class(将包从 test.dto 更改为您在其中创建 class 的任何内容):

select new test.dto.EmpDTO(o.empNo, o.empName) from Emp o

最后编辑您的代码:

...
public List<EmpDTO> findAll() {
    Query query = getEntityManager().createNamedQuery("Emp.findAll");
    return query.getResultList();
}

顺便说一句:Emp.findAll 不是您的 namedQuery 的理想名称。