如何从JPA EntityManager获取返回的对象作为自定义bean

时间:2017-05-28 14:49:11

标签: java spring hibernate jpa

我正在尝试使用entityManager.createQuery加入3个表来获取所需信息。

代码littlepet如下:

List<Object[]> o=entityManager.createQuery("SELECT u.loginId,ui.emailId,u.userId,ui.firstName,up.password,ui.phoneNunber,u.roleTypeId"  + " From Users as u,UserInfo ui, UserPassword as up where u.userId = up.userId "    + "AND u.userId=ui.userId").getResultList();

我有一个带有上述返回字段UserDetails的bean。

public class UserDetails
{
    String LoginId;
    String Email;
    String UserId;
    String FirstName;
    String Password;
    String Mobile;
    String RoleTypeId;
    int Status;

getters() & setters()
}

但是,当我尝试使用List UserDetails代替List Object[]ClassCastException。{/ p>

如何使用自定义bean获取/转换返回的对象?

2 个答案:

答案 0 :(得分:3)

 List<UserDetails> o=entityManager.createQuery("SELECT new package.UserDetails( u.loginId,ui.emailId,u.userId,ui.firstName,up.password,ui.phoneNunber,u.roleTypeId)"  + " From Users as u,UserInfo ui, UserPassword as up where u.userId = up.userId "    + "AND u.userId=ui.userId").getResultList();

您需要具有参数的构造函数与查询中选择的字段的顺序相同,因此 UserDetails(loginId,emailId,userId,firstName,password,phoneNunber,roleTypeId)

或者您可以使用您的代码,然后编写一个转换器,将一组对象转换为 UserDetails

 List<Object[]> retrievedObjects = //yourCode.
 for (Object[] objs : retrievedObjects) {
      //write convert method which populates **UserDetails** fields from the objects.
      UserDetails ud = convert(objs);
 }

答案 1 :(得分:1)

您可以使用结果转换器。结果转换器是一个Hibernate功能(不是JPA)。因此,您需要使用Hibernate中的SessionQuery

这样的事情:

List<UserDetails> result = entityManager.createQuery(
  "SELECT u.loginId as loginId, ui.emailId as emailId ..."
).unwrap(org.hibernate.query.Query.class)
 .setResultTransformer(new AliasToBeanResultTransformer(UserDetails.class))
 .list();

您需要在HQL中添加别名:u.loginId as loginId以及UserDetails中的相应属性:

class UserDetails
{

  private String loginId;

  public String getLoginId() {
    return loginId;
  }

  public void setLoginId(String loginId) {
    this.loginId = loginId;
  }

}

变形金刚的例子: http://jpwh.org/examples/jpwh2/jpwh-2e-examples-20151103/examples/src/test/java/org/jpwh/test/querying/advanced/TransformResults.java