skip to Main Content

I am trying to insert user record using mysql database

Customer.java

@Entity
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstname;
    private String lastname;
    @Column(unique = true)
    private String email;
    @Column(nullable = false)
    private String password;
    @Column(unique = true, nullable = false)
    private String username;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<Role> roles;
}

CustomerController

    @PostMapping("/customer")
    public void addCustomer(@RequestBody Customer customer) {
        customerService.createCustomer(customer);
    }

CustomerService

@Service
public class CustomerService {
    public CustomerService(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    public void createCustomer(Customer customer) {

        customerRepository.save(customer);
    }
}

Role.java

public class Role {

    @Id
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "roles")
    private Set<Customer> customers;
}

JSON Ojbect

{
  "firstname": "John",
  "lastname": "Doe",
  "email": "[email protected]",
  "password": "john",  // Ensure that passwords are hashed and never stored in plain text
  "username": "john123",
  "roles" : [1]
}

2

Answers


  1. The JSON object shared seems to be incorrect, try using the following

    {
        "firstname": "John",
        "lastname": "Doe",
        "email": "[email protected]",
        "password": "john",
        "username": "john123",
        "roles": [
            {
                "id": 1
            }
        ]
    }
    

    Since roles is a list of complex object Role, you need to enclose each object of Role in a {}.

    Hope this helps!

    Good luck!

    Login or Signup to reply.
  2. The JSON object provided in your request should correctly map to the Role entity(It has id, name properties).

    If you want to pass roles as objects, then the JSON should be this,

    {
      "firstname": "John",
      "lastname": "Doe",
      "email": "[email protected]",
      "password": "john",  // Ensure that passwords are hashed and never stored in plain text
      "username": "john123",
      "roles" : [
        {"id": 1, "name": "ROLE_USER"}
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search