1

I'm trying to learn spring boot with JPA. How to create an entity that only has selected columns of a table? I can do this using jdbcTemplate but is it also possible using JPA?

I tried using the SELECT NEW but it gives me a null pointer exception error on the em.createQuery execution. Does it mean I get no results? Can you help me pinpoint my error?

Here is my code :

EntityManager em;

    String queryStr =
            "SELECT NEW com.lms.app.user.User(c.id.username, c.password, c.emailadd) FROM TBUSER AS c";
    TypedQuery<User> query =
            em.createQuery(queryStr, User.class);
    List<User> results = query.getResultList();

User.class

public class User {

private String name;
private String password;
private String email;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
}

TBUSER columns looks like this :

username varchar (primary key)
password
emailadd
then more columns here..
Dekso
  • 541
  • 4
  • 23
  • Try this: [Spring data jpa - the best way to return object](https://stackoverflow.com/a/46878744/5380322) – Cepr0 May 24 '18 at 09:55
  • related to https://stackoverflow.com/questions/24710626/jpa-query-selecting-only-specific-columns-without-using-criteria-query?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Sheetal Mohan Sharma May 24 '18 at 09:58
  • Thanks I used jdbcTemplate. – Dekso Jun 04 '18 at 04:00

0 Answers0