0

Is it possible to map not the entire entity but just one of its columns with Hibernate? I have User and Role entities. Each user can have multiple roles, however I'd like to fetch only titles of the roles.

What I want:

class User {
    private Set<String> roles;
}

What I don't want:

class User {
    private Set<Role> roles;
}

Is it possible to achieve this somehow via ManyToMany relation, with a single query or maybe some other option? Without using DTO and copying role titles after fetching?

Thank you.

p.s. I have 3 tables: one for users, one for roles and one for connecting user to roles.

John Smith
  • 63
  • 8
  • What you want is a String[] or Set. – K.Nicholas Jul 31 '18 at 17:20
  • Yes. Use a projection to get the column you want – Dan Jul 31 '18 at 17:21
  • are you using JPA's @Query annotation, a Criteria Query? How are you querying for the data? – Dan Jul 31 '18 at 17:21
  • Projections not exactly what I want. I'd like a fully constructed User entity with role names. As far as I understand to use a projection I will have to create an interface. I could achieve the same with a simple DTO object. I'm looking for something without creating additional class/interface. @Dan for querying the data I'm using primarily EntityManager and sql queries. – John Smith Jul 31 '18 at 17:57
  • 1
    I just answered someone's question using some code that might help your situation. See if this helps: https://stackoverflow.com/questions/51618138/how-to-avoid-child-of-child-objects-in-spring-jpa#51619141 – Dan Jul 31 '18 at 18:10
  • Essentially, use a native query to pull what you need and avoid the things you do not want. You'll have to create a mapper to do so, however. – Dan Jul 31 '18 at 18:12
  • @Dan thanks man. I'll go with mapper if no better option appears. – John Smith Jul 31 '18 at 18:22
  • I agree with @K.Nicholas. His link should give you what you're looking for – Dan Jul 31 '18 at 19:10

1 Answers1

0

A custom User constructor could work:

class User {
    private List<Role> roles;  // changed to List for easier access

    User(String fName, String lName, String roleName, long roleId){
          this.fName=fName;
          this.lName=lName;
          this.roles = new ArrayList<>();
          this.roles.get(0).setRoleName(roleName);
          this.roles.get(0).setRoleId(roleId);
    }
}

Then issue your query: select new your.package.User(u.firstName, u.lastName, u.role.name, u.role.id) from User u where ...

Dan
  • 979
  • 1
  • 8
  • 29