简体   繁体   中英

Hibernate/JPA map Result of native Query to non-Entity holding Entities

I do have 3 Entities and want to Cross-Join them. As I do not need to create a new Entity for this I just wanted to map the by fetching with a native Query:

EntityA{
    ...
    String someValue;
}

EntityB{
    ...
    String someValue;
}

EntityC{
    ...
    String someValue;
}

And the CrossJoined Object

CrossJoinedFoo{
    EntityA entityA;
    EntityB entityB;
    EntityC entityC;
}

I am using it like:

private static final String _SELECT_CROSS_JOIN_ENTITIES = "SELECT * FROM "
            + "EntityA"
            + ", "
            + "EntityB"
            + ", "
            + "EntityC"
            + " WHERE (1=1) "
            + " AND " + "EntityA.someValue = :someValue"
            + " AND " + "EntityB.someValue = :someValue"
            + " AND " + "EntityC.someValue = :someValue";

Query query = entityManager.createNativeQuery(_SELECT_CROSS_JOIN_ENTITIES);
query.setParameter(":someValue", "foo");

How can I achieve this behavior?

You can go for a HQL query and use the result class strategy. Just remember to add a constructor to CrossJoinedFoo accepting 3 entities in appropriate order:

private static final String _SELECT_CROSS_JOIN_ENTITIES = 
            "SELECT new my.package.CrossJoinedFoo(a,b,c) FROM "
            + "EntityA a"
            + ", "
            + "EntityB b"
            + ", "
            + "EntityC c"
            + " WHERE (1=1) "
            + " AND " + "a.someValue = :someValue"
            + " AND " + "b.someValue = :someValue"
            + " AND " + "c.someValue = :someValue";

Query query = entityManager.createQuery(_SELECT_CROSS_JOIN_ENTITIES);
query.setParameter(":someValue", "foo");

List<CrossJoinedFoo> result = query.list();

Just remember to change the package to an appropriate one.

Using @SqlResultSetMapping with @ConstructorResult

Beware that the resulted entities won't be managed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM