Issue
I am trying to create a OneToOne relationship between two entities but I get this error:
@OneToOne or @ManyToOne on backendservice.entity.BookingEntity.roomId references an unknown entity: long
My entities
@Data
@Entity(name = "bookings")
public class BookingEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fk_roomId", referencedColumnName = "id")
private Long roomId;
@Column(name = "booked_by")
private String bookedBy;
@Column(name = "date_booked")
private String dateBooked;
}
@Data
@Entity(name = "rooms")
public class RoomEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "room_name")
private String roomName;
@OneToOne(mappedBy = "fk_roomId")
private BookingEntity bookingEntity;
}
Solution
In the association field you should use an actual entity, not just Long field. So this code:
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fk_roomId", referencedColumnName = "id")
private Long roomId;
should be changed on something like
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fk_roomId", referencedColumnName = "id")
private RoomEntity room;
Additionally I would like to note that for performance considerations it is highly recommended to declare your associations as lazy:
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
Answered By - Eugene