我确实有3个实体,想要交叉加入它们。由于我不需要为此创建新的实体,我只想通过使用本机查询来获取:
EntityA{
...
String someValue;
}
EntityB{
...
String someValue;
}
EntityC{
...
String someValue;
}
和CrossJoined对象
CrossJoinedFoo{
EntityA entityA;
EntityB entityB;
EntityC entityC;
}
我正在使用它:
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");
我该如何实现这种行为?
答案 0 :(得分:3)
您可以使用HQL查询并使用结果类策略。 只需记住向CrossJoinedFoo添加一个构造函数,以适当的顺序接受3个实体:
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();
请记住将包更改为合适的包。
答案 1 :(得分:1)
将@SqlResultSetMapping
与@ConstructorResult
请注意,结果实体不会成为managed