JPA正在更新@OneToMany的@ManyToOne

时间:2018-01-29 09:18:58

标签: jpa

无法从permission更新projectPermission的参考project,请参阅以下实体供您参考

Project.java

@OneToMany( cascade = CascadeType.MERGE, orphanRemoval = true,
                        mappedBy = "project", fetch = FetchType.LAZY )
private List<Projectpermission> permissions = new ArrayList<Projectpermission>();

ProjectPermission.java

@ManyToOne
@Column( nullable = false )
private Permission permission;

@ManyToOne
@JoinColumn( name = "PPM_PRJ_ID", nullable = false )
private Project           project;

JSON要更新的对象

{
    "projectDescription": "Jeta description",
    "permissions": [{
        "projectPermissionId": 2551,
        "person": "XXX",
        "permission": {
            "permissionName": "read",
            "permissionId": 2
        }
    } ],
    "projectName": "Jeta",
    "projectId": 2
}

在更新project时,projectPermission应该更新,但在成功更新后获取null作为对projectPermission数组的响应。

更新后的响应

{
    "projectDescription": "Jeta description",
    "permissions": [],
    "projectName": "Jeta",
    "projectId": 2
}

1 个答案:

答案 0 :(得分:0)

project反向引用添加到projectpermission使更新生效,所有引用的projectpermission也与项目一起保存,因此permission上的projectpermission已被保存}}。请查看以下代码段以供参考,

    List< Projectpermission > permissions = project.getPermissions();
    ArrayList< Projectpermission > updatedProjectPermissionsList = new ArrayList< Projectpermission >();
    for ( Projectpermission projectPermissions : permissions ) {
        projectPermissions.setProject( project ); // <- solution setting the project backreference to the individual permission entity makes it work
        updatedProjectPermissionsList.add( projectPermissions );
    }
    project.getPermissions().addAll( updatedProjectPermissionsList );
    Project updateProject = projectRepositoryBeanLocal.updateProject( project );