All Pereira
All Pereira

Reputation: 149

Spring Rest - Field with @ManyToOne mapping is null

I have the below scenario:

  1. 2 entities, User and Company;
  2. I'm using H2database;
  3. I persist a Company and everything is OK and id 1 is returned;
  4. When I try to save a User to Company, my field company_id in database, is empty. I don't know what is happening! See my json to persist a user:

    { "id": null, "name": "My Name", "login": "My Login", "mail":"[email protected]", "password":"secret", "federalID":"0000000", "company":{"id": 1} }

I'll no post Controllers and other class, just will show de important to solve this. Below the classes used with your maps.

The User class:

@Entity(name = "users")
@Table(name = "users")
@EqualsAndHashCode
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String login;
    private String mail;
    private String password;
    private String federalID;
    @ManyToOne(optional = false, cascade = CascadeType.ALL)
    @JoinColumn(name = "company_id", referencedColumnName="company_id")
    private Company company;
}

The Company class:

@Entity(name="companies")
@Table(name="companies")
@EqualsAndHashCode
@Data
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String federalID;
    @OneToMany(mappedBy="company", targetEntity=User.class, fetch=FetchType.EAGER) 
    private List<User> users;
}

Rest of User Entity (Company Controller follow the same pattern):

@RestController
public class UsersController {

    @Autowired 
    UserRepository userRepository;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public List<User> getUsers(){
        return userRepository.findAll();
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable("id") Long id){
        return userRepository.findById(id);
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public ResponseEntity<User> createUser(@RequestBody User company){
        return new ResponseEntity<>(userRepository.save(company), HttpStatus.CREATED);
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id){
        userRepository.delete(id);

        return new ResponseEntity<Void>(HttpStatus.OK);
    }

}

Upvotes: 2

Views: 2599

Answers (1)

Abdullah G&#252;rsu
Abdullah G&#252;rsu

Reputation: 3186

As you can see,Company is a relation on your User class. Due to the fact that, Hibernate cannot recognize it as an initialized entity. To resolve the problem, you should manually load the Company by using company_id and you should set the loaded company into the User class insideUserController.

Upvotes: 2

Related Questions