Home > Mobile >  springboot with MongoDb ,Transient field return null
springboot with MongoDb ,Transient field return null

Time:06-24

When i trying to do my RBAC job , I've made a class RolePermission like belows:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class RolePermission extends BaseEntity{
    private Long roleId;
    private Long permissionId;
    @Transient
    private List<Permission> permissions;
    public RolePermission(Long roleId,Long permissionId){
        this.roleId = roleId;
        this.permissionId = permissionId;
    }
}

class Permission like belows

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Permission extends BaseEntity{

    public Permission(Long id, Long parentId, String name){
        this.setId(id);
        this.parentId = parentId;
        this.name = name;
    }
    private String name;
    private Long parentId;
    private String url;
    private String permission;
    private Integer type;
    private String icon;
    private Integer status;
    private Integer ord;
}

Here comes my test :

LookupOperation lookup = Aggregation.lookup("permission", "roleId", "_id", "permissions");
        Aggregation aggregation = Aggregation.newAggregation(lookup);
        AggregationResults<RolePermission> role_permission = mongoTemplate.aggregate(aggregation, "role_permission", RolePermission.class);
        //AggregationResults<Map> role_permission = mongoTemplate.aggregate(aggregation, "role_permission", Map.class);
        System.out.println(role_permission.getMappedResults());
        //userService.getAllPermissions(u);

When I add @Transient , permissions comes to null enter image description here

and When I remove @Transient,permissions comes back. enter image description here

I don't wanna save permissions to MongoDB, so I add @Transient, is there any way i can draw the data back without saving it to the Database. Because I get the permissions data from a relationship collectionRolePermission,not itself.

CodePudding user response:

The @Transient behaves similar to the transient keyword.

transient is used to denote that a field is not to be serialized (and therefore not saved in the database too).

@Transient is used to denote that a field should not persisted in database (but it is still serializable as java object).

Take look this baeldung tutorial for it: https://www.baeldung.com/jpa-transient-ignore-field

There is no way to draw the data back without saving it to the Database because it isn't persisted at all since it is what @Transient is used for.

To get the data back you have to persist it somewhere else, but the best place is in the database. If you don't want to persist it along with the other data, consider saving it in a sperate database. So, you could split user data and authentication/RBAC data.

  • Related