0

I'm building a spring boot backend for my final year project. API's from the Products package is working properly. But when I call addUser Api which is located inside Users Package I got this {" ids for this class must be manually assigned before calling save()"} error. And I get error code 500 in response.

I have tried Implementing componentscan annotation in the application root and many other solutions. But nothing worked for me.

Github Repo Link

Solutions I Tried So Far

Solution 1 Solution 2

Creator
  • 303
  • 4
  • 23

2 Answers2

0

Answered here before

You haven't shared the API request, and I'm guessing you're not passing the correct parameters for the User class. The class also doesn't have an ID generation strategy, coupled with an incorrect request body will give you the mentioned error.

EDIT: Your UserRepository extends CrudRepository<User, Integer> defines a repository with an Integer primary key, however the entity has a String id field, you may want to correct that as well.

Tahir Mustafa
  • 323
  • 1
  • 10
0

Here is the problem

@Entity 
public class User {
    @Id
    String user_Id;

  }

You have declared user_Id to be the primary key of the table. Therefore it is must not be null. I am sure that in your controller you pass the object User without providing a key. In many cases we leave the database to create a primary key, but in your case it does not work that way. So you must provide a user_Id for your User before calling .save()

That is the reason for the error that you get

 {" ids for this class must be manually assigned before calling save()"}

If you wish to get automatically a value for your key, either from JPA or from your database you must provide another anonnotation the @GeneratedValue and select an option. But for that to work you must change your id field from String to Long or Integer.

Here is an example of how that could work

@Entity 
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

  }

GenerationType. has many other options.

Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47