A Contract has several AbsenceType, and an AbsentType can be in several different Contracts. So I made a manyToMany relation in both classes.
Entity
@Table(name = "contract")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
@EntityListeners(AuditingEntityListener.class)
public class Contract {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "employee")
private int employee;
@ManyToMany(mappedBy = "contracts")
private List<AbsenceType> absence_types;
// ... getteur setteur contructor
@Entity
@Table(name = "absence_type")
@EntityListeners(AuditingEntityListener.class)
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class AbsenceType {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
// hexa : #FFFFFF
@Column(name = "color")
private String color;
@Column(name = "is_paid")
private boolean is_paid;
@ManyToMany
@Column(name = "contracts")
private List<Contract> contracts;
// ... getteur setteur contructor
I want to be able to create empty Absence types and then when I create a contract, give in my json, the previously created absenceType and not create a new AbsenceType.
In the idea I do this:
{
"id": 1 # Exemple, in real in don't had id on json
"name": "Congé sans solde",
"color": "ff4040",
"is_paid": false,
"contracts": []
}
and after ->
{
"name": "Contract4",
"employee": 3,
"absence_types" : [
{
"id":1
}
]
}
But the response when i get all contracts is:
{
"id": 621,
"name": "Contract4",
"employee": 3,
"absenceTypes": []
}
But i want :
{
"id": 621,
"name": "Contract4",
"employee": 3,
"absenceTypes": [
{
"id": 1,
"name": "Congé sans solde",
"color": "ff4040",
"contracts" : [ dudo, i don't think about infinite recursion problem for the moment haha]
}
}
For all of my DAO i have a generic class, how look like this
public void save(T obj) {
Session session = openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(obj);
transaction.commit();
session.close();
}
and on my Contract controller
@PostMapping("")
public ResponseEntity<String> create(@RequestBody Contract contract) {
// Error 422 if the input role variable is null
if (contract == null)
new ResponseEntity<String>("Can't create null absenceType", HttpStatus.UNPROCESSABLE_ENTITY);
contractDAO.save(contract);
return new ResponseEntity<>("absenceType saved !", HttpStatus.OK);
}