英文:
JAVA JPA returning few Entity variables with their names using interface
问题
以下是您要求的翻译内容:
假设我有一个简单的类:
public class Human{
private String id;
private String name;
private String surname;
private String something;
private String something2;
//getters setters
}
并且我声明了一个接口:
public interface IHuman{
String getId();
String getName();
}
在我的仓库中,我调用了:
@Query("select r from Human r")
Page<IHuman> getIdAndName();
这将返回一个包含 id 和 name 属性的 IHuman 数组,但在转换为 JSON 时,它没有变量名称,只返回值:
"content":[["id1","jeff"],["id2","Jones"],...]
所以我的问题是:是否可能使用接口将变量连接到它们对应的值,以获得类似以下的结果:
"content":[{"id":"id1","name":"jeff"},{"id":"id2","name":"Jones"},...]
英文:
Lets say I have a simple class:
public class Human{
private String id;
private String name;
priavte String surname;
priavte String something;
priavte String something2;
//geters setters
}
and I have declared an Interface
public interface IHuman{
String getId;
String getName;
}
in my repository I call:
@Query("select r from Human r")
Page<IHuman> getIdAndName();
Which in turn returns me an array of IHuman atributes with id and name, but when parsing to JSON it has no variable names and returns only the values:
"content":[["id1","jeff"],["id2","Jones"],...]
so my question would be: is it possible to connect variables to their corresponding values using interface, to get something like:
"content":[["id":"id1","name":"jeff"],["id":"id2","name":"Jones"],...]
答案1
得分: 1
以下是您要翻译的内容:
您正在编写以下代码:
@Query("select r from Human r")
Page<IHuman> getIdAndName();
这将返回整个 `Human` 对象。
但是您只需要 id 和 name,因此在查询中只检索这些内容,就像这样:
```java
@Query("select r.id, r.name from Human r")
Page<IHuman> getIdAndName();
这样应该可以将您的接口与值进行映射。
英文:
You are writing
@Query("select r from Human r")
Page<IHuman> getIdAndName();
Which would return entire Human
object.
But you only need id and name, so only retrieve that in the Query, like
@Query("select r.id, r.name from Human r")
Page<IHuman> getIdAndName();
And That should map your interface with your values.
答案2
得分: 0
我真的不知道这是怎么/为什么起作用的,但是没问题:
将查询更改为:
@Query("SELECT r.id as Id, r.name as Name from human r")
Page<IHuman> getIdAndName();
然后在我的 IHuman 类中添加:
@Value("#{target.Id}")
String getId();
@Value("#{target.Name}")
String getName();
英文:
I legit don't know how/why this worked, but ok:
switched Query to:
@Query("SELECT r.id as Id, r.name as Name from human r)
Page<IHuman> getIdAndName();
and in my IHuman class I added:
@Value("#{target.Id}")
String getId();
@Value("#{target.Name}")
String getName();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论