How to return a Map where the key is an entity property and the value is the entity with JPA and Hibernate

Nemanja Žunić :

Say for example I have an sql table

create table CUSTOMER
(
  first_name      VARCHAR2(30) not null,
  last_name       VARCHAR2(30) not null,
  age             VARCHAR2(30) not null,
  credit_card_num VARCHAR2(30) not null UNIQUE
);

and I want to get a Java Map where the map keys are values of CUSTOMER.credit_card_num and the map values are all the properties of CUSTOMER so for example:

1234134cardnumber -> Customer(first_name: Jack, age: 23, credit_card_num: 1234134cardnumber),
123faef -> Customer(first_name: Mike, age: 43, credit_card_num: 123faef)

etc...

I'll accept any way to do it in JPA or Native Query

Update

as kindly referred by https://stackoverflow.com/users/1025118/vlad-mihalcea it can be done by https://vladmihalcea.com/why-you-should-use-the-hibernate-resulttransformer-to-customize-result-set-mappings/

Vlad Mihalcea :

Since this is a very common question, I wrote this article, on which this answer is based on.

There are two solutions to this problem.

Assuming you are using the following Post entity:

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @Column(name = "created_on")
    private LocalDate createdOn;

    public Long getId() {
        return id;
    }

    public Post setId(Long id) {
        this.id = id;
        return this;
    }

    public String getTitle() {
        return title;
    }

    public Post setTitle(String title) {
        this.title = title;
        return this;
    }

    public LocalDate getCreatedOn() {
        return createdOn;
    }

    public Post setCreatedOn(LocalDate createdOn) {
        this.createdOn = createdOn;
        return this;
    }
}

And you have the following entities persisted in your database:

entityManager.persist(
    new Post()
        .setId(1L)
        .setTitle("High-Performance Java Persistence eBook has been released!")
        .setCreatedOn(LocalDate.of(2016, 8, 30))
);

entityManager.persist(
    new Post()
        .setId(2L)
        .setTitle("High-Performance Java Persistence paperback has been released!")
        .setCreatedOn(LocalDate.of(2016, 10, 12))
);

entityManager.persist(
    new Post()
        .setId(3L)
        .setTitle("High-Performance Java Persistence Mach 1 video course has been released!")
        .setCreatedOn(LocalDate.of(2018, 1, 30))
);

entityManager.persist(
    new Post()
        .setId(4L)
        .setTitle("High-Performance Java Persistence Mach 2 video course has been released!")
        .setCreatedOn(LocalDate.of(2018, 5, 8))
);

entityManager.persist(
    new Post()
        .setId(5L)
        .setTitle("Hypersistence Optimizer has been released!")
        .setCreatedOn(LocalDate.of(2019, 3, 19))
);

Using a Java 8 Stream

Here's how you can return a Map as requested by your question:

Map<Long, Post> postByIdMap = entityManager
.createQuery(
    "select p " +
    "from Post p ", Post.class)
.getResultStream()
.collect(
    Collectors.toMap(
        Post::getId,
        Function.identity()
    )
);

assertEquals(
    "High-Performance Java Persistence eBook has been released!",
    postByIdMap.get(1L).getTitle()
);

assertEquals(
    "Hypersistence Optimizer has been released!",
    postByIdMap.get(5L).getTitle()
);

Using a Hibernate ResultTransformer

The same goal can be achieved using a ResultTransformer:

Map<Long, Post> postByIdMap = (Map<Long, Post>) entityManager
.createQuery(
    "select p " +
    "from Post p ")
.unwrap(org.hibernate.query.Query.class)
.setResultTransformer(
    new ResultTransformer() {

        Map<Long, Post> result = new HashMap<>();

        @Override
        public Object transformTuple(Object[] tuple, String[] aliases) {
            Post post = (Post) tuple[0];
            result.put(
                post.getId(),
                post
            );
            return tuple;
        }

        @Override
        public List transformList(List collection) {
            return Collections.singletonList(result);
        }
    }
)
.getSingleResult();

assertEquals(
    "High-Performance Java Persistence eBook has been released!",
    postByIdMap.get(1L).getTitle()
);

assertEquals(
    "Hypersistence Optimizer has been released!",
    postByIdMap.get(5L).getTitle()
);

For more details about the ResultTransformer, check out this article.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358298&siteId=1
Recommended