如何在Hibernate Panache中执行仅选择部分列的数据库查询?

huangapple go评论73阅读模式
英文:

How to do db query that selects only partial columns in Hibernate Panache?

问题

  1. // 返回部分列
  2. List<Object[]> results = panacheRepo.find("select id, name from tableName where lastName = 'abc'").list();
英文:

How can I translate below query to Hibernate Panache?
(using PostgresSql)

  1. Select t.id, t.name from tableName as t where t.lastName = &quot;abc&quot;;

For returning all columns it is straight forward.

  1. Select * from tableName as t where t.lastName = &quot;abc&quot;;
  2. //becomes
  3. panacheRepo.find(&quot;lastName&quot;, lastName);

Is there a similar way when I want to select only partial columns?

Or if not possible with Hibernate Panache what about with plain Hibernate?

答案1

得分: 1

通过Panache,您可以使用查询投影

  1. @Entity(name = "Person")
  2. @Table(name = "tablename")
  3. public class Person extends PanacheEntity {
  4. public String name;
  5. public LocalDate birth;
  6. public Status status;
  7. }
  8. @RegisterForReflection
  9. public class PersonName {
  10. public final String name;
  11. public PersonName(String name){
  12. this.name = name;
  13. }
  14. }
  15. // 仅从数据库加载'name'
  16. Person.find("status", Status.Alive).project(PersonName.class);

如果您使用纯Hibernate,可以在HQL或SQL查询中指定选择子句。

例如:

  1. List<Object[]> results = session.createQuery(
  2. "select p.name, p.status from Person p", Object[].class)
  3. .getResultList();
英文:

With Panache, you can use query projection:

  1. @Entity(name = &quot;Person&quot;)
  2. @Table(name = &quot;tablename&quot;)
  3. public class Person extends PanacheEntity {
  4. public String name;
  5. public LocalDate birth;
  6. public Status status;
  7. }
  8. @RegisterForReflection
  9. public class PersonName {
  10. public final String name;
  11. public PersonName(String name){
  12. this.name = name;
  13. }
  14. }
  15. // only &#39;name&#39; will be loaded from the database
  16. Person.find(&quot;status&quot;, Status.Alive).project(PersonName.class);

If you are using plain Hibernate, you can specify the select clause in the HQL or SQL query.

For example:

  1. List&lt;Object[]&gt; results = session.createQuery(
  2. &quot;select p.name, p.status from Person p&quot;, Object[].class)
  3. .getResultList();

huangapple
  • 本文由 发表于 2023年4月1日 00:53:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定