4

I try to create a function in my backend for create a user, I use to Spring Boot, Hibernate, JPA, PostgreSQL... This is my code:

User.java

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

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

    @NotNull
    @NotBlank
    @Size(max = 100)
    @Column(name = "firstName")
    private String name;

    @NotNull
    @NotBlank
    @Size(max = 30)
    @Column(name = "username", unique = true)
    private String username;

    @NotNull
    @NotBlank
    @Size(max = 150)
    @Column(name = "password")
    private String password;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cityId", nullable = false)
    @JsonIgnore
    private City city;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "countryId", nullable = false)
    @JsonIgnore
    private Country country;

    // Getters and Setters
    ...
}

UserController.java

@PostMapping("/users/{countryId}/{cityId}")
public User createUser(@PathParam(value = "countryId") Long countryId, @PathParam(value = "cityId") Long cityId,
        @Valid @RequestBody User user) {
    user.setCountry(countryRepository.findById(countryId)
            .orElseThrow(() -> new ResourceNotFoundException("Country not found with id " + countryId)));
    user.setCity(cityRepository.findById(cityId)
            .orElseThrow(() -> new ResourceNotFoundException("City not found with id " + cityId)));
    return userRepository.save(user);
}

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByCountryId(Long countryId);

    List<User> findByCityId(Long cityId);
}

I use Postman for make a test. I try to create a user with this URL (1 = countryID, 4 = cityId) and Payload:

URL

localhost:8080/users/1/4

Payload

{
    "name": "David",
    "username": "david",
    "password": "test",
}

and I received this error...

ERROR:

{
    "timestamp": "2018-05-07T13:44:03.497+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!",
    "path": "/users/1/4"
}

2018-05-07 14:25:40.484 ERROR 17964 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!] with root cause

But I don't know how resolve this problem

5
  • The server should point to what line the issue is caused by. Without knowing the cause, it may be @Valid as you have no id for your User you are creating. Commented May 7, 2018 at 13:56
  • This is the server information give me: "2018-05-07 14:25:40.484 ERROR 17964 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!] with root cause" Commented May 7, 2018 at 13:58
  • What's your DB manager? Oracle or MySQL Commented May 7, 2018 at 13:59
  • My DB manager is PostgreSQL Commented May 7, 2018 at 14:00
  • Do you have values for the country and city of id 1 and 4 respectively and did debug give u both values set into user object? Since you have marked both entity relationship as not null, I'm just wondering. Commented May 7, 2018 at 14:34

2 Answers 2

5

You should set the data type of id column in PostgreSQL to SERIAL

Change @PathParam to @PathVariable should work.

You're using the wrong annotations.

Edit

Spring uses annotation to do some special logic to extract values from request URI or from request body and map them to appropriate annotated parameter.

You're using the wrong annotation on parameter so its value is not populated.

When your repository execute code to find against null will throw exception

Sign up to request clarification or add additional context in comments.

2 Comments

The same error... I think the problem it's in the url... but I don't know how solver
Could you give a website o pdf for study more about this? or reading about this? :)
-2

Simply do not use Long. Use the primitive type long for you id.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

This will initiate the field id with 0 if not available, which will solve the problem.

In general, try to avoid complex data types if you also can use the simple data type. Every time you use a complex over a simple data type, there has to be a good reason. Otherwise it's mostly a bad smell.

6 Comments

I changed it but it's the same error... Code: "@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id;"
Even if it solves problem, what do you think of a table with all primary key id = 0?
@MạnhQuyếtNguyễn It will generate a new key, as this is the standard behaviour when annotating with @GeneratedValue. This is the default way to handle this.
@Manu are you sure you've recompiled your project in a clean way? long cannot be null.
Sure! but I have the same error, I think the problem its how send cityId and countryId in the URL... It's right?: ("/users/{countryId}/{cityId}") --> localhost:8080/users/1/4
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.