I have created These two Entities
Language:
import jakarta.persistence.*;
@Entity
public class Language {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String langName;
private String paradigm;
}
User:
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
@ManyToOne(cascade = CascadeType.ALL)
private Language language;
}
So we have several programmers and each programmer has a favourite Language. Multiple Programmers can have same favourite language.
I am trying to create a microService which I will send data to(via an endpoint) and get stored in a database.
I am confused as to how should I be sending my data. Should I first populate the Language Entity, then start populating the User Entity and everytime I add a Users object, I check whether the corresponding language is present in Language Entity or not?
Or should I directly start with the User Entity sending all the fields along with his/her language, make a check whether it exists in the Language Entity, if it exists fetch its id and assign it to the User foreign key, if it does not exist, then insert it along with the Person Object?
I am using the JpaRepository interface for CRUD.
You should load language first. If you using UI then you must have some predefined languages so if language is loaded then you can show them in ui.
While sending user you can pass only id and hibernate will check if id exists then map that id without loading whole object from db.
Add constructor with argument id Language
class.
public Language(long id) {
this.id = id;
}
Sample user JSON.
{
"name": "Tony",
"language": 1
}
OR will also work
{
"name": "Tony",
"language": {
"id": 1
}
}
When you save User
entity then it will automatically map Language with id 1.
When you send JSON your controller will receive object. Spring JacksonMapper will convert json to object.
@RestController
public class UserController {
@PostMapping(value = "/users")
public ResponseEntity<Void> createUser(@RequestBody @Valid User userVO) {
}
}