greenfly
greenfly

Reputation: 63

Hibernate. How to map two entities into one?

I have two tables in DB and two entities. HtmlDesc and HtmlData.

Both with the same id. Is there a way to create compund/merged entity in Hibernate without repeating code from this two entities. I want to execute statment

Query<Html> query = getCurrentSession().createNativeQuery(
            "SELECT * FROM HtmlDesc A, HtmlData B WHERE A.linkId = B.linkId",
            Html.class);
return query.getResultList();

to map to new entity Html = HtmlDesc+HtmlData. Is there some smart code to write such entity?

Afterwards i found related topic which can be helpful if someone have similar problem: JPA- Joining two tables in non-entity class

Upvotes: 0

Views: 498

Answers (1)

mayuran siva
mayuran siva

Reputation: 26

if my understanding of your question is correct @SqlResultSetMapping is what you are looking for.

This will provide custom mapping where entity manager will be able to map the list of objects to specific entities

As an example for your case

List<Object[]> results = em.createNativeQuery("select * from html h JOIN htmla ha ON h.id=ha.id","HtmlaHtmlbMapping").getResultList();

@SqlResultSetMapping(
    name="HtmlaHtmlbMapping",
    entities = {
            @EntityResult(
                    entityClass = HTML.class,
                    fields = {
                            @FieldResult(name="id",column = "id"),
                            @FieldResult(name = "detail", column = "detail")}),
            @EntityResult(
                    entityClass = HTMLA.class,
                    fields = {
                            @FieldResult(name="id",column = "id"),
                            @FieldResult(name = "name", column = "name")})})

Upvotes: 1

Related Questions