【发布时间】:2021-07-20 16:47:15
【问题描述】:
我正在使用带有 JPA 的 springboot 来创建 REST API。我想从学生那里获取所有详细信息,并从地址中获取匹配行(如果存在)。
下面是我的服务实现
EntityManager entityManager = entityManagerFactory.createEntityManager();
query = entityManager.createQuery("select s , a from Student s " +
" left join Address a " +
" on s.id = a.student ")
@SuppressWarnings("unchecked")
List<Object> list = query.getResultList();
下面是我的学生实体
@Entity
class Student{
private int id,
private String name,
@ManyToOne(optional = false)
@NotNull
@JsonIgnoreProperties(value = "student", allowSetters = true)
private User user; // User another entity
--- getter and setter --
}
以下是我的地址实体
class Address{
private int id;
private String addressLine;
@ManyToOne(optional = true)
@JsonIgnoreProperties(value = "address", allowSetters = true)
private Student student;
--- getter and setter --
}
所以它会返回所有匹配的行,其关系属性如下所示
[{
id :1,
name: "qwert",
user:{
id: 1,
createdBy:1
createdOn:2021-08-21
}
}
{
id: 1,
addressLine:"kkkkk",
student{
id :1,
name: "qwert",
user{
id: 1,
createdBy:1
createdOn:2021-08-21
}}}]
**I want output be like below**
[
{
id :1,
name: "qwert",
user:{
id: 1
}},
{
id: 1,
addressLine:"kkkkk"
}]
我们怎样才能做到这一点?我尝试使用 POJO 但无法实现。我是 Springboot 和 JPA 的初学者。是否有另一种方法可以从不相关的实体中获取数据并返回带有特定字段的 POJO。
【问题讨论】:
标签: java spring-boot spring-data-jpa