我怎样才能避免创建多余的实体? [英] How can I avoid the creation of superfluous entities?

查看:94
本文介绍了我怎样才能避免创建多余的实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我当前的项目中,我需要执行一些原生查询,它们从查询中加入的表中选择一些字段,例如:

  SELECT t1.col1,t2.col5 
FROM t1
JOIN t2 ON t2.id = t1.t2_id

我尝试将它们存储在类中,如

  class Result {
String t1_col1 ;
字符串t2_col5;

使用

 查询q = entityManager.createNativeQuery(THE SQL SELECT,Result.class); 

JPA现在抱怨(uknown entity:result)类'result'不是可能需要将列映射到对象中的实体。
我也尝试在结果类中重复 @Column 声明。



我的问题是我可以声明这一点,而不必在数据库中创建表示的实体吗?

执行SQL查询,那么你正在使用错误的工具。 Hibernate是一个ORM,你应该将表映射到实体。这是JPA的重点。我只是想执行SQL查询,使用JDBC(例如Spring的JdbcTemplate)

一旦table1和table2被映射到实体(让我们称之为实体T1和T2) ,您将不再需要这些SQL查询,因为JPQL只能选择实体的某些字段。你的查询可能是这样的(取决于t1和t2之间的关联):

  select t1.col1,t2.col5从T1 t1加入t1.t2 t2 

你只需迭代结果(这是一个DTO而不是一个映射实体):

  List< Object [] > rows =(List< Object []>)query.list(); 
清单<结果> listOfResults = new ArrayList< Result>(rows.size);
for(Object [] row:rows){
listOfResults.add(new Result((String)row [0],(String)row [1]));
}


In my current project I need to perform a few native queries which pick some fields from tables joined in the query e.g.:

SELECT t1.col1, t2.col5
FROM t1
JOIN t2 ON t2.id = t1.t2_id

I tried to store them in a class like

class Result {
  String t1_col1;
  String t2_col5;
}

using

Query q = entityManager.createNativeQuery( "THE SQL SELECT" , Result.class );

JPA now complains ("uknown entity: result") that the class 'result' isn't an entity which is probably required to map the columns into the object. I also tried to repeat the @Column declarations in the result class.

My question is how can I declare this without having to create the entites represented as tables in my DB?

解决方案

If you're using JPA/Hibernate to perform SQL queries, then you're using the wrong tool. Hibernate is an ORM, and you're supposed to map tables to entities. That's the whole point of JPA. I you just want to perform SQL queries, use JDBC (and Spring's JdbcTemplate for example)

Once table1 and table2 are mapped to entities (let's call these entities T1 and T2), you won't need these SQL queries anymore, because JPQL is able to select only some fields of the entities. Your query could the look like this (depending on the association between t1 and t2):

select t1.col1, t2.col5 from T1 t1 join t1.t2 t2

And you would just have to iterate over the result (a list of Object[]) to build your results (which is a DTO and not a mapped entity) :

List<Object[]> rows = (List<Object[]>) query.list();
List<Result> listOfResults = new ArrayList<Result>(rows.size);
for (Object[] row : rows) {
    listOfResults.add(new Result((String) row[0], (String) row[1]));
}

这篇关于我怎样才能避免创建多余的实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆