0

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

In service class I have the following code

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

The problem is generated JSON doesn't have attribute names, e.g.

["2390","JAMES"],

Whereas if I change namedQuery in Emp class to

select o  from Emp o

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?

Jacob
  • 14,463
  • 65
  • 207
  • 320

3 Answers3

3

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.

You can change the query as below

select new Emp(o.empNo, o.empName) from Emp o and have a constructor in your class accordingly.

or try using

select new Map(o.empNo as empNo , o.empName as empName) from Emp o

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
1

The difference is that in the query select o.empNo, o.empName from Emp o you select specific entity fields and the every result row is an Object[]. Thus that array of the specified properties.

The second query select o from Emp o selects the entire entity with all its fields, and what you see is the JSON-marashalled entity.

V G
  • 18,822
  • 6
  • 51
  • 89
1

In the first case, your JPQL returns a List<Object[]>; each item in the list is an array containing the values of o.empNo and o.empName. Of course, when JSON is produced, it is produced as an array/list of items.

In the second case, you get a List<Employee>, which each item being an Employee instance, so it is serialized like an object would be (list of attribute-values).

SJuan76
  • 24,532
  • 6
  • 47
  • 87