Search code examples
javaspring-boothibernatehibernate-mapping

Having problems with foreign key in Hibernate


I have 2 tables Room and Guest

@Entity
@Table(name = "rooms")
public class Room
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String type;
private String image;
private double price;
@Column(columnDefinition = "TEXT")
private String description;

    @OneToOne
    @JoinColumn(name = "guest_id", referencedColumnName = "id")
    private Guest guest;`
@Entity
@Table(name = "guests")
public class Guest
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String phone_num;
    private String email;
    private LocalDate check_in_date;
    private LocalDate check_out_date;

    @OneToOne(mappedBy = "guest", cascade = CascadeType.ALL)
    private Room room;

I am trying to use Hibernate to create foreign key in Room table which is supposed reference 'id' field in my Guest table. I am also trying to display contents of my Room table in table using Bootstrap

<td th:text = "${room.guest_id}"></td>

But I am however getting this problem: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'guest_id' cannot be found on object of type 'com.example.hotel.Room.Room' - maybe not public or not valid?

Here is also my room controller if needed:

@Controller
@RequestMapping("/rooms")
public class RoomController
{
    @Autowired
    private RoomRepository roomRepository;

    @GetMapping("/")
    public String showRooms(Model model)
    {
        List<Room> rooms = roomRepository.findAll();
        model.addAttribute("rooms", rooms);

        return "rooms";
    }
}

Is the problem with the way I am trying to create foreign key or the controller that I have? Massive thanks in advance!


Solution

  • Your model is a bit wrong:

    @JoinColumn(name = "guest_id", referencedColumnName = "id")
    private Guest guest;`
    

    You do not need the referencedColumnName = "id" here.

    And you are mixing database attribute with java attribute:

    <td th:text = "${room.guest_id}"></td>
    

    You have to write:

    <td th:text = "${room.guest.id}"></td>
    

    The JPA Annotation (@JoinColumn, etc...) is only to reference the table in database and write proper SQL: you can omit them and let your JPA implementation (hibernate) use some default unless you already have a database or unless you have constraints (or formalism) on the name.