Tengo 2 entidades, una es User
y la otra Absences
, y estoy intentando hacer POST para crear una ausencia relacionada con un User
concreto, su "dueño". La ausencia se crea correctamente con el campo Date
y el campo String comment
, pero no logro recoger al usuario a través de su id con el JSON de la petición. No sé si me equivoco en formular el JSON o el problema está en la lógica de java-spring que he construido.
He tratado varias maneras, como pasar por @Requestbody
solo Absence
y que el service se encargue de los parámetros de Absence
y User
a través de absence.getStudent()
para ver si recogía la relación directamente, que yo creo que quizás sería lo más lógico, pero tampoco funciona... Ando atascado ya..
@Entity
public class Absence {
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@JsonView(View.Summary.class)
private int id;
@Nullable
@JsonView(View.SummaryWithOthers.class)
private Date dateMissing;
@Nullable
@JsonProperty(access = Access.READ_WRITE)
@JsonView(View.SummaryWithOthers.class)
private String comment;
@ManyToOne (fetch = FetchType.EAGER)
@JsonView(View.Summary.class)
@JoinColumn (name="student_id", nullable = false)
private MyAppUser userStudent;
@Entity
@Table(name="users")
public class MyAppUser {
//@GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@JsonView(View.Summary.class)
private String id;
@JsonView(View.Summary.class)
private String firstName;
@JsonView(View.Summary.class)
private String lastName;
@JsonView(View.SummaryWithOthers.class)
private String email;
@JsonView(View.SummaryWithOthers.class)
private char gender;
@JsonView(View.SummaryWithOthers.class)
private int age;
@JsonView(View.SummaryWithOthers.class)
private String portrait;
@JsonView(View.Summary.class)
@ManyToOne
private Seat seat;
@JsonView(View.SummaryWithOthers.class)
@ManyToOne
private Absence userAbsence;
@ManyToOne (fetch = FetchType.EAGER)
@JoinColumn (name="rol_id")
private Role role;
private String password;
private boolean enabled;
private Date lastLogin;
@OneToMany (targetEntity = Absence.class, cascade = CascadeType.ALL)
private List <Absence> absences = new ArrayList <Absence>();
@OneToMany (targetEntity = Course.class, cascade = CascadeType.ALL)
@JsonView(View.Summary.class)
public List <Course> courses = new ArrayList <Course>();
@OneToMany (targetEntity = UserExercice.class, cascade = CascadeType.ALL)
private List <UserExercice> userExercices = new ArrayList <UserExercice>();
@OneToMany (targetEntity = Emails.class, cascade = CascadeType.ALL)
private List <Emails> emails = new ArrayList <Emails>();
@OneToMany(mappedBy="myAppUser")
@JsonIgnore
Set<UserIteration> userIterations;
MyAppUser Repository
public interface MyAppUserRepository extends JpaRepository<MyAppUser, String>{
public ArrayList<MyAppUser> findByFirstName(String firstName);
public ArrayList<MyAppUser> findByLastName(String lastName);
public List<MyAppUser> findByGender(char gender);
public ArrayList<MyAppUser> findByRoleId(int roleId);
Optional <MyAppUser> findOneById(String id );
MyAppUser findUserById(String id );
}
Controller
//Create absence by student id
@PostMapping("/api/students/absences")
public Absence createAbsence(@RequestBody Absence absence, MyAppUser userStudent) {
return absencesService.createAbsence(absence, userStudent);
//return absencesService.createAbsence(absence, absence.getUserStudent().getId())
//-->Usando solo Absence como RequestBody! Hay que tener en cuenta 4 cambios pequeños en Service claro está...
}
Service
public Absence createAbsence(Absence absence, MyAppUser userStudent) {
String studentId = userStudent.getId();
//absence.getUserStudent().getId();
Absence absenceCreated = new Absence();
userStudent = myAppUserRepository.findUserById(studentId);
absenceCreated.setComment(absence.getComment());
absenceCreated.setDateMissing(absence.getDateMissing());
absenceCreated.setUserStudent(userStudent);
myAbsenceRepository.save(absenceCreated);
return absenceCreated;
}
JSON in POSTMAN
{
"userStudent": {
"student_id":"58a55a41-04cc-4007-a322-e7bb969e626b"
},
"dateMissing": "1574541388697",
"comment": "prueba"
}
POSTMAN me devuelve lo siguiente:
{
"id": 485,
"dateMissing": 1574541388697,
"comment": "prueba",
"userStudent": null
}
Soy un novato en Spring y sus anotaciones, no me lo tengan en cuenta ^^
Gracias a todos!