生成的JSON中缺少JPA Entity属性名称 [英] JPA Entity attribute names missing in generated JSON
问题描述
我正在使用JPA并且Jackson用于生成JSON
I am using JPA and and Jackson is used for generating JSON
Emp.java
@Entity
@NamedQuery(name = "Emp.findAll",
query = "select o.empNo, o.empName from Emp o ")
@Table(name = "EMP")
public class Emp implements Serializable {
@Column(name = "ename")
private String empName;
@Id
@Column(name = "empno", nullable = false)
private String empNo;
.....
在服务类我有以下代码
@GET
@Path("/emplist")
@Produces(MediaType.APPLICATION_JSON)
public Object getEmployees() {
List<Emp> list = this.findAll();
ObjectMapper objectMapper = new ObjectMapper();
empAsJson = objectMapper.writeValueAsString(list);
public List<Emp> findAll() {
return getEntityManager().createNamedQuery("Emp.findAll").getResultList();
}
生成问题JSON没有属性名称,例如
The problem is generated JSON doesn't have attribute names, e.g.
["2390","JAMES"],
然而,如果我将Emplass中的namedQuery更改为
Whereas if I change namedQuery in Emp class to
select o from Emp o
然后生成JSON的属性名称如下所示
then generated JSON has attribute names as shown below
[{"empNo":"2390","empName":"JAMES"},
这可能是什么原因以及如何解决这个问题?
What could be the reason for this and how can I resolve this issue?
推荐答案
NAmed查询选择o.empNo,来自Emp o
的o.empName将返回List< Object []>
where as 从Emp o
中选择o将返回List< Emp>
,因此 json
将被生成。
NAmed Query select o.empNo, o.empName from Emp o
will return List<Object[]>
where as select o from Emp o
will return List<Emp>
, so accordingly json
will be produced.
您可以更改以下查询
选择来自Emp o
的新Emp(o.empNo,o.empName)并在您的班级中有一个构造函数相应地。
select new Emp(o.empNo, o.empName) from Emp o
and have a constructor in your class accordingly.
或尝试使用
选择新地图(o.empNo as empNo ,来自Emp o的o.empName为empName)
这篇关于生成的JSON中缺少JPA Entity属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!