spring hibernate did not get the value of parameter

I try to make an API call with the post method via postman to my spring boot application. Here is the input:

{
  "username": "name",
  "password": "1234",
  "age": 12,
  "salary": 5000,
  "role": 1
}

Here is the code in the controller:

@RequestMapping(value = "/topic/signup", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> saveUser(@RequestBody UserDto user) {
        try {
            System.out.println(user.getUsername()); // => name
            System.out.println(user.getPassword()); // => 1234
            System.out.println(user.getSalary()); // => 5000
            System.out.println(user.getRole()); // => 1
            System.out.println(user.getAge()); // => 12
            userService.save(user);
            return ResponseEntity.ok().body("insert done");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

Here is my User.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@Column
@JsonIgnore
private String password;
@Column
private long salary;
@Column
private int age;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "role_id")
private Role role;
// getters and setters

Here is my Role.java

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "role_name", nullable = false)
private String roleName;
// getters and setters

Here is my UserDto.java

private String username;
private String password;
private int age;
private long salary;
private int role;
// getters and setters

Here is my RoleDto.java

private Long id;
private String roleName;
// getters and setters

Problem: it throws error 'Column 'role_id' cannot be null'

Here is in the userServiceImpl: Below line (BeanUtils) is refer to here.

    @Override
    public User save(UserDto user) throws Exception {
        User newUser = new User();
        BeanUtils.copyProperties(user, newUser, "password");
        newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
        try {
            userDao.save(newUser);
        } catch (Exception e) {
            throw new Exception(e);
            // this throw "Column role_id cannot be null"
        }
        return newUser;
    }

But, if I use below code, the setRole method is not applicable since I define user.getRole() in the DTO as int but define newUser.setRole() in the User entity as Role. But if I change the setRole in User entity as int, then, how I can tell the spring about the ManyToOne relation between User and Role?

@Override
public User save(UserDto user) throws Exception {
    User newUser = new User();
    newUser.setUsername(user.getUsername());
    newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
    newUser.setAge(user.getAge());
    newUser.setSalary(user.getSalary());
    newUser.setRole(user.getRole()); // here is the problem
    try {
        userDao.save(newUser);
    } catch (Exception e) {
        throw new Exception(e);
    }
    return newUser;
}

Note: I think I just want to make the input parameter for role to be just an integer as provided above.

Since you are receiving 1 for the role in your request you should do something like:

Role role = new Role();
role.setId(user.getRole());
role.setRoleName("some name");
newUser.setRole(role);

In the first part of the code the problem may be here BeanUtils.copyProperties(user, newUser, "password");, if you try to debug or print newUser after that line you will see that BeanUtils was not able to populate correctly all the fields of your newUser object. And this is because in the destination (newUser) the field role is of type Role, while in the source (user) the type of that field is just int.

after hours of trying i found a way to make it work.

first i add @namedstoredprocedurequery to my companyresource entity class:

companyresource.java

@entity
@table(name = "company_resource")
@namedstoredprocedurequeries({
        @namedstoredprocedurequery(name = "getallmetalfromcompaniesbyplayerid",
                                    procedurename = "getallmetalfromcompaniesbyplayerid",
                                    parameters = {
                                        @storedprocedureparameter(mode = parametermode.in, name = "playerid", type = integer.class),
                                        @storedprocedureparameter(mode = parametermode.out, name = "metalsum", type = bigdecimal.class)
                                    })
})
@idclass(companyresourcepk.class)
public class companyresource {
...
}

then i changed my getmetalresourcebyplayerid() method in companyresourceserviceimpl as followed:

companyresourceserviceimpl.java

@service
public class companyresourceserviceimpl implements companyresourceservice {

@persistencecontext
    private entitymanager entitymanager;

...

private int getmetalresourcebyplayerid(int theid) {

        storedprocedurequery thequery = entitymanager.createnamedstoredprocedurequery("getallmetalfromcompaniesbyplayerid");

        thequery.setparameter("param1", theid);

        bigdecimal outamount = (bigdecimal) thequery.getsingleresult();

        return  outamount.intvalue();
    }

...

}

this solved my problem with the soapaction:

[soapdocumentservice(routingstyle = soapserviceroutingstyle.requestelement)]

soapserviceroutingstyle enumeration soapaction the soap message is routed based on the soapaction http header. requestelement the soap message is routed based on the first child element following the xml element of the soap message.

in addition to removing and adding web-reference, you could try regenerating proxies using wsdl.exe as suggested here, with the namespace again. hope it helps

this was resolved. details on the issue related to this can be found at: https://github.com/spring-projects/spring-security/issues/5535#issuecomment-407413944

example project that is now working: https://github.com/ericis/oauth-cf-https-issue

the short answer:

the application needs to be explicitly configured to be aware of the proxy headers. i had tried configuration, but ultimately had to use an instance of the forwardedheaderfilter class that was added fairly recently to spring.

@bean
filterregistrationbean<forwardedheaderfilter> forwardedheaderfilter() {

    final filterregistrationbean<forwardedheaderfilter> filterregistrationbean = new filterregistrationbean<forwardedheaderfilter>();

    filterregistrationbean.setfilter(new forwardedheaderfilter());
    filterregistrationbean.setorder(ordered.highest_precedence);

    return filterregistrationbean;
}

Tags: Java Spring Boot Crud