So I have the following entity:
@Entity
@Table(name = "appointment")
public class Appointment {
@EmbeddedId
private AppointmentId id = new AppointmentId();
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("customerId")
@JoinColumn(name = "customerId") //Remember to use joincolumns to rename the generated column is spring creates it
private Customer customer;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("barberId")
@JoinColumn(name = "barberId") //Remember to use joincolumns to rename the generated column is spring creates it
private Barber barber;
@Column(name = "notes")
private String notes;
public Appointment(Customer customer, Barber barber, String notes) {
this.customer = customer;
this.notes = notes;
this.barber = barber;
}
public Appointment() {
}
@JsonBackReference
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Override
public String toString() {
return "Appointment{" +
", notes='" + notes + '\'' +
'}';
}
}
And this is the AppointmentId
:
@SuppressWarnings("serial")
@Embeddable
public class AppointmentId implements Serializable {
private Integer barberId;
private Integer customerId;
}
Now I was following a tutorial in which I managed to accomplish what I wanted to do. The key was to add the @EmbeddedId
annotation and create the AppointmentId class.
I currently have 3 records in my 'Appointment' table in the DB. And each record has a primary key and the value is 1,2,3 resepctively.
I'm trying to fetch the 2nd record so I'm using the .findById(2)
method from my interface which extends JpaRespository<Appointment, Integer>
but I get the following error. I'm not sure why:
org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.gogobarber.barber.entities.Appointment. Expected: class com.gogobarber.barber.entities.AppointmentId, got class java.lang.Integer
I mean the error is self explantory.. it's asking for the ID in the form of AppointmentId
but how can I create such an object without knowing the customer or the barber id?
EDIT = This is my table schema for Appointments:
Table: appointment
Columns:
idappointment int AI PK
notes varchar(255)
barberId int
customerId int
EDIT =
Controller:
@DeleteMapping("/appointment/{appointmentId}")
public void deleteAppointment(@PathVariable String appointmentId)
{
appointmentService.deleteAppointment(appointmentId);
}
Service:
@Transactional
public void deleteAppointment(String appointmentId) {
appointmentRepo.deleteById(Integer.valueOf(appointmentId));
}