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
The JSON object shared seems to be incorrect, try using the following
Since roles is a list of complex object Role, you need to enclose each object of Role in a
{}
.Hope this helps!
Good luck!
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,