Java – how to avoid creating redundant entities?

In my current project, I need to execute some native queries. These queries select some fields from the tables connected in the query, such as:

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

I try to store them in similar classes

class Result {
  String t1_col1;
  String t2_col5;
}

application

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

JPA now complains that the ("UKNOW entity: result") class "result" is not an entity that may need to map columns to objects I also try to repeat the @ column declaration in the result class

My question is how to declare this without having to create entities represented as tables in my database?

Solution

If you use JPA / hibernate to execute SQL queries, you are using the wrong tool Hibernate is an orm. You should map tables to entities This is the focus of JPA I just want to execute SQL queries and use JDBC (such as spring's jdbctemplate)

Once table1 and table2 are mapped to entities (let's call these entities T1 and T2), you will no longer need these SQL queries, because jpql can only select some fields of entities Your query might look like this (depending on the association between T1 and T2):

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

You only need to iterate the result (object [] list) to build your result (this is a dto rather than 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]));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>