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

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

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

问题

// 返回部分列
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)

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

For returning all columns it is straight forward.

Select * from tableName as t where t.lastName = &quot;abc&quot;;
//becomes 
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,您可以使用查询投影

@Entity(name = "Person")
@Table(name = "tablename")
public class Person extends PanacheEntity {
    public String name;
    public LocalDate birth;
    public Status status;
}

@RegisterForReflection 
public class PersonName {
    public final String name; 

    public PersonName(String name){ 
        this.name = name;
    }
}

// 仅从数据库加载'name'
Person.find("status", Status.Alive).project(PersonName.class);

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

例如:

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

With Panache, you can use query projection:

@Entity(name = &quot;Person&quot;)
@Table(name = &quot;tablename&quot;)
public class Person extends PanacheEntity {
    public String name;
    public LocalDate birth;
    public Status status;
}

@RegisterForReflection 
public class PersonName {
    public final String name; 

    public PersonName(String name){ 
        this.name = name;
    }
}

// only &#39;name&#39; will be loaded from the database
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:

List&lt;Object[]&gt; results = session.createQuery(
	&quot;select p.name, p.status from Person p&quot;, Object[].class)
.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:

确定