Home > Software design >  Why can not persist data in spring data jpa
Why can not persist data in spring data jpa

Time:01-18

While save data in database got exception Cannot handle managed/back reference 'defaultReference': back reference type not compatible with managed type. I got exception while persist data. I think problem is in @JsonManagedReference or @JsonBackReference annotation but can't findout the problem.

Here down is code...

Entity

@Entity
@Table(name = "user_master")
public class Users {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer user_id;

    private String name;

    @JsonManagedReference
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
            @JoinColumn(name = "role_id") })
    private List<Roles> roles;

    // constructor and getter/setter
}

@Entity
@Table(name = "role_master")
public class Roles {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer role_id;

    private String name;

    @JsonBackReference
    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "roles")
    private List<Users> users;

    // constructor and getter/setter
}

Service

@Override
    public List<Users> addUserRole(List<Users> users) {
        for(Users user: users)
        {
            for(Roles role: user.getRoles())
            {
                role.getUsers().add(user);
            }
        }
        return userRepo.saveAll(users);
    }

Controller

@RequestMapping(value = "/adduserrole", method = RequestMethod.POST)
    public ResponseEntity<List<Users>> addUserRole(@RequestBody List<Users> users)
    {
        pojoService.addUserRole(users);
        return ResponseEntity.ok(users);
    }

Postman

{
    "name": "Jack",
    "roles": [
    {
        "name": "Engineer"
    },
    {
        "name": "Doctor"
    },
    {
        "name": "Charter Accountant"
    }
    ]
}

Exception

{
    "timestamp": "2022-01-18T11:04:03.573 00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Type definition error: [simple type, class com.rest.RestApiPojo.Entity.Users]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (`java.util.List<com.rest.RestApiPojo.Entity.Users>`) not compatible with managed type (com.rest.RestApiPojo.Entity.Users)\n at [Source: (PushbackInputStream); line: 1, column: 1]",
    "path": "/adduserrole"

CodePudding user response:

You have to do following changes

  1. Remove the users list from the roles and just keep list of roles inside the User entity.

  2. Remove @JsonManagedReference, if you just want to output roles, jackson will handle those for you.

  3. You might want to consider one-to-Many (user-to-Roles) as one directional relationship as it's not ideal to consider one role could have many users, and we do not want to load entities in persistent level like that. ex:-

         @OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
         @JoinTable(
         name = "user_role",
         joinColumns = @JoinColumn(
                 name = "user_id",
                 referencedColumnName = "id"
         ),
         inverseJoinColumns = @JoinColumn(
                 name = "role_id",
                 referencedColumnName = "id"
         ))
    

CodePudding user response:

Please try with the below post body as your request body accepting List.

{
"users": [
{
    "name": "Jack",
    "roles": [
    {
        "name": "Engineer"
    },
    {
        "name": "Doctor"
    },
    {
        "name": "Charter Accountant"
    }
    ]
  }
  ]
}
  •  Tags:  
  • Related