我一直在使用 JPA 构建一个 JSF 应用程序来访问数据库。有许多实体。
我想创建一个搜索结果屏幕,显示表中多个实体的列。这些实体没有外键关系。
为此,我使用了 EnttityManager.createNativeQuery 并指定了 EntityMapping,如下所示:
Query q = em.createNativeQuery(
"select t.id as id1, t.bb as bb1, t.cc as cc1," +
"t2.id as id2, t2.aa as aa2, t2.bb as bb2 " +
" from table1 t, table2 t2 where t.cc = '22' and t2.id = 2", "TestMapping");
result = q.getResultList();
测试映射看起来像这样:
@SqlResultSetMapping(name =
"TestMapping", entities = {
@EntityResult(entityClass = Table1.class, fields = {
@FieldResult(name = "id", column = "id1"),
@FieldResult(name = "bb", column = "bb1"),
@FieldResult(name = "cc", column = "cc1")}
),
@EntityResult(entityClass = Table2.class, fields = {
@FieldResult(name = "id", column = "id2"),
@FieldResult(name = "aa", column = "aa2"),
@FieldResult(name = "bb", column = "bb2")}
)
} )
如果我从查询中的两个实体中指定所有列名,则此方法有效,这在这个小示例中很好,但搜索结果必须从 4 个实体中选择,所有这些实体都有大量列。如果我没有指定 EntityMapping 中的所有列,则会在调用 getResultList() 时引发异常。
我的问题是:是否可以仅指定查询中选择的 EntityMapping 中的列,而不必从实体中指定所有列?