Skip to content
Advertisement

How to save array of object in sprig boot with crudrepository?

I am very new to Spring boot and this is my first spring dummy project where I’m trying to learn to save an array of objects in mysql-db.

Actually, I am trying to use the saveAll method from the crudRepository in my controller. But it’s giving me an error no instance(s) of type variable(s) S exist so that Iterable<S> conforms to List<User>

My JSON looks like this:

JavaScript

This is my entity class

JavaScript

Here is my User Model Class

JavaScript

Here is my repository

JavaScript

and here is my rest controller

JavaScript

Can anyone please help me? This is ery first time I am usig spring boot

Advertisement

Answer

You have some problems about your code:

At first you have a DTO (User class), so, you should use this DTO inside your controller in saveUsers method and more importantly you pass an array of objects in your JSON, so you have to use a List not an Object as the parameter:

JavaScript

Another problem is you don’t have any getters and setters inside you DTO (public class User) and Entity (public class UserEntity) classes and also you have to add a method inside your DTO class for mapping DTO to Entity:

JavaScript

Also you must change your JSON properties to match your DTO’s properties:

JavaScript

As the last one, change your controller saveUsers method as (saveAll method return Iterable not List):

JavaScript

Notice: As a point remember that because you have auto-generated id inside your Entity, so you don’t need id property for your DTO, obviously because it’s auto-generated and you don’t need to get it from input;

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement