0

Im making a small application where i can save user details using spring-boot. i created the entities and their corresponding repositories. When ever i make a post request to add a user the id of the user object which is null at the point of saving to the data base.This id is auto generated(Auto Increment) in MySQL. From the POST request i get 3 fields which are username,email,password. The User class contains fields id,username,email,password. I've added the annotations

@Id 
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;

for the id field. an the constructors are

public User() { }

public User(String username, String email, String password) {
    this.username = username;
    this.email = email;
    this.password = password;
}

This is the error im getting. enter image description here

The debugging process enter image description here

my userService class

    @Service
    public class UserService implements UserServiceInterface {

        @Autowired(required = true)
        private UserRepository userrepository;

        @Override
        public User CreateNewUser(User user) {
            return userrepository.save(user);
        }
}

my userController class

@RestController
    public class UserController {

        UserService us = new UserService();

        @RequestMapping(value ="/user",method = RequestMethod.POST)
        public void RegisterUser(           
                @RequestParam(value="username") String username,
                @RequestParam(value="email") String email,
                @RequestParam(value="password") String password){
            us.CreateNewUser(new User(username,email,password));
        }
}

Any reason why i cant POST to save data to database? how to overcome this?

Madushika Perera
  • 402
  • 2
  • 5
  • 13
TRomesh
  • 4,323
  • 8
  • 44
  • 74
  • 1
    an NPE WHERE? Any exception should be posted with its stack trace since it shows whose code is responsible. Clearly an object can be passed to the JPA API without setting any `@GeneratedValue` field and its value will be assigned in the datastore – Neil Stockton Mar 18 '17 at 06:41
  • @NeilStockton I have edited the question – TRomesh Mar 18 '17 at 06:49
  • @NeilStockton UserService is the class where im doing all the functionalities of user. eg saving user info,delete(Basic CRUD) – TRomesh Mar 18 '17 at 06:54
  • @NeilStockton i have added both UserService and UserController file – TRomesh Mar 18 '17 at 07:32

1 Answers1

0

After digging through the code i found out the error. by creating a new instance of UserService us = new UserService(); this is not managed by Spring (Spring doesn't know about it and cannot inject UserRepository - this causes NullPointerException). there of instead of creting new instace it should extends the UserService class in this example.

TRomesh
  • 4,323
  • 8
  • 44
  • 74