Named Query to Return List <String>

Hello I am using dropwizard for my application.

Resource class

@Path("/people")
@Produces(MediaType.APPLICATION_JSON)
public class PeopleResource{

    private PersonDAO pdao;

    public PeopleResource(PersonDAO pdao) {
        this.pdao = pdao;
    }

    @GET
    @Timed
    @UnitOfWork
    public List<String> getAllPeople() {
        return pdao.findAll();
    }
}

      

DAO class

public class PersonDAO extends AbstractDAO<Person> {

public PersonDAO(SessionFactory factory) {
    super(factory);
}

public List<String> findAll() {
    return list(namedQuery("com.example.findAll"));
}

public Person create(Person p) {
    return persist(p);

}

      

Person class

@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "Person")

@NamedQueries({
    @NamedQuery( 
            name = "com.example.findAll",
            query = "SELECT distinct p.name FROM Person p"
    )
})

@JsonProperty
String name;

      

But when I try to access the resource it always fails stating that in the DAO class the findAll method should return List<Person>

instead List<String>

. What am I missing? I checked the query against the database and returned the correct result. Is there a way to customize the return type of the query inside namedQuery?

+3


source to share


2 answers


Try deleting the shared List like this:

public List findAll() {
  return list(namedQuery("com.example.findAll"));
}

      



It seems to be passed to a list of strings and then you can use generics further down the chain.

0


source


Change your list method and use a typed query



TypedQuery<String> query =
      em.createNamedQuery("com.example.findAll", String.class);
  List<String> results = query.getResultList();

      

0


source







All Articles