JPA

How to get custom object from a query instead of object[] when you query for multiple properties of an Entity?

Suppose you have a Customer entity,

Customer.java
public class Customer implements Serializable{
private Long id;
private String firstName;
private String lastName;
private Long mobileNo;
private String houseNo;
private String street;
//setters and getters
}
Query query = entityManager.createQuery("SELECT customer.firstName, customer.mobileNo FROM Customer customer WHERE customer.id = 10");
If you execute the above query you will get an Object[], then you have to typecast each array element into corresponding type, this is rediculous.

So you need to do like the below,
Query query  = entityManager.createQuery("SELECT new MinCustomer(customer.firstName, customer.mobileNo) FROM Customer customer WHERE customer.id = 10");


MinCustomer minCustomer = query.getSingleResult();
And create a class MinCustomer with argumentative constructor as given below

MinCustomer.java

public class MinCustomer{

private String firstName;
private Long mobileNo;

public MinCustomer(String firstName, Long mobileNo){
this.firstName = firstName;
this.mobileNo = mobileNo;
}
}

No comments:

Post a Comment