简体   繁体   中英

How to get a list to a constructor through jpql query

I need to pass a list to a VO (Value Object) through a JPQL query. For example:

My VO class:

public class FamilyVO {
  private String lastName;
  private List<Name> names;

  public FamilyVO () {
  }

  public FamilyVO (List<Name> names, String lastName) {
    this.names = names;
    this.lastName = lastName;
  }
}

My query using the new operator:

public class FamilyRepositoryBean {

    @Override
    public List<FamilyVO> findFamilies(Long id) {

        StringBuilder jpql = new StringBuilder("SELECT new "+ FamilyVO.class.getName());
        jpql.append("(f.names, f.lastName)");
        jpql.append(" FROM Family f ");
        jpql.append(" WHERE f.id = :pId");

        Query query = em.createQuery(jpql.toString());
        query.setParameter("pId", id);

        return query.getResultList();
    }
}    

My entity Family:

@Entity
public class Family  {

    @OneToMany(mappedBy = "family")
    protected List<Name> names = new ArrayList<Name>();

    private String lastName;

    public Family() {
    }

    public List<Name> getNames(){
        return names;
    }

    public String getLastName() {
       return lastName;
    }
}

My entity Name:

@Entity
public class Name  {

   @NotNull
   @ManyToOne(fetch = FetchType.LAZY, optional = false)
   private Family family;    

   public Name() {
   }

   public Family getFamily(){
        return family;
   }

}

When I run this query, the following error occurs:

RuntimeException on EJB call java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class

If you make a constructor with parameters; you should provide the constructor with no parameters, explicity;

public FamilyVO (){ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM