英文:
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 = "abc";
For returning all columns it is straight forward.
Select * from tableName as t where t.lastName = "abc";
//becomes
panacheRepo.find("lastName", 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 = "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;
}
}
// only 'name' will be loaded from the database
Person.find("status", 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<Object[]> results = session.createQuery(
"select p.name, p.status from Person p", Object[].class)
.getResultList();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论