Issue
I am trying to make a connection between an Event
and User
entity, so that I can save entrants into an event. I have never used @ManyToMany
mapping before and so have been following a tutorial. When I try to post the data via postman (eventid
and userid
), I get null values for both.
So far I have, User and Event entity,
@Data
//Entity maps object to database
@Entity
@NoArgsConstructor
@Table(name = "member")
public class User implements UserDetails, Serializable {
//More fields
//Relationship between user and events to get entrants
@OneToMany(mappedBy = "userid", fetch = FetchType.LAZY)
Set<Entrants> entrants;
@Data
//Entity maps object to database
@Entity
@NoArgsConstructor
@Table(name = "event")
public class Event implements Serializable {
//More fields
//Relationship with event and users for entrants to an event
@OneToMany(mappedBy = "eventid",fetch = FetchType.LAZY)
Set<Entrants> entrants;
Then I have an Entrant Entity to hold the entrants to an event.
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Entrants implements Serializable {
@Id
@GeneratedValue
Long id;
@ManyToOne
@JoinColumn(name = "user_id")
User userid;
@ManyToOne
@JoinColumn(name = "event_id")
Event eventid;
}
Then in my controller,
@PostMapping("/management/events/entrants")
GenericResponse createEntrant(@Valid @RequestBody Entrants entrant) {
System.out.println("entrant is: " +entrant);
entrantService.save(entrant);
return new GenericResponse("Entrant saved");
}
EntrantService
public Entrants save(Entrants entrants) {
return entrantRepository.save(entrants);
}
and the repository is the standard and the above utilises the save() method.
If I post the following in Postman,
{
"user_id": 1,
"event_id": 1
}
I get this
entrant is: Entrants(id=null, userid=null, eventid=null)
id
is obviously created by Spring, but the userid
and eventid
are null.
From my limited knowledge I think this is something to do with the 2 fields in the Entrants
entity, being of type User
and Event
rather than int
. But I am not sure how to get around this.
The tutorial I followed wasnt really based on my implementation so I have had to change quite a lot.
Solution
You could use a Dto in your controller like this:
@PostMapping("/management/events/entrants")
createEntrant(@Valid @RequestBody EntrantDto entrant) {
System.out.println("entrant is: " +entrant);
entrantService.save(entrant);
return new GenericResponse("Entrant saved");
}
EntrantDto.java
public class EntrantDto {
private Long user_id;
private Long event_id;
// no-args constructor, getter, setter,...
}
and modify a little bit your service like
public Entrants save(EntrantDto entrant) {
User user = this.userRepository.findById(entrant.getUser_id()).orElseThrown(IllegalArgumentException::new);
Event event = this.eventRepository.findById(entrant.getEvent_id()).orElseThrown(IllegalArgumentException::new);
Entrants entrants = new Entrants(user, event);
return entrantRepository.save(entrants);
}
Answered By - Linh Vu