【问题标题】:Wrapping a multi level mapping associated entity by parent entity按父实体包装多级映射关联实体
【发布时间】:2018-01-09 06:32:00
【问题描述】:

我有实体组织、员工、角色

@Entity
public class Organization
{
....
@OneToMany
List<Employee> employees;
}

@Entity
public class Employee
{
....
@OneToMany
List<Role> roles;
}

@Entity
public class Role
{
....
String roleName;
}

我希望为所有与实体(可以是组织、员工或角色)无关的获取结果保持相同的结构,这些实体将具有所需的实体字段,所有其他字段将为空。

假设我有角色列表。我可以通过以下代码实现我的要求

 Employee employee = new Employee();
 employee.setRoles(roles );
 Organization org = new Organization();
 org.setEmployee(employee);

。但是没有上面的setter和constructor代码,有什么方法可以实现下面的结构吗?

{
 ...
  employees:[
    roles:[
          {
          ...
          },
           {
            ....}
           ],
           ....
           ]
 }

有什么办法吗?

【问题讨论】:

  • 请添加更详细的描述,说实话我不知道你在问什么

标签: java json hibernate jpa spring-data


【解决方案1】:

如果我正确理解Employee 有roleId。如果是这种情况,您可以使用 @JoinColumn 在 Employee.class 中设置 Role role 对象而不是 Long roleId:

@ManyToOne
@JoinColumn(name="roleId", referencedColumnName="id")
private Role role;

请记住,name="roleId" 是 Employee.class 中的字段,referencedColumnName="id" 是 Role.class 中的 id 字段

【讨论】:

  • 我的代码中有。在这里,我只是在我的问题中错过了这一点。通过它,我将获得相关的对象。我正在使用@JsonManagedReference 和@JsonBackReference。所以我的organisationRepository.findAll() 会将我的输出作为给定的 json 结构给出。但我希望roleRepository.findAll() 结果也被组织对象包裹
  • 为什么不创建OrganizationDTO.class,它将包含来自Organization.class 和List&lt;Employee&gt; employees 的所有信息。您的员工名单将从您的employeeRepository? 填写
猜你喜欢
  • 2012-05-25
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
相关资源
最近更新 更多