I'm working on a small project involving the game Re-Volt (1999), I'm trying to make a web page where you can see all the cars with their details (image, engine type, rating, speed etc.). I have a table cars
where I the previous mentioned information and it looks like this:
CREATE TABLE public.cars (
id integer NOT NULL,
name character varying(25),
thumbnail_id integer,
engine_id integer,
rating_id integer,
speed integer,
acc numeric,
mass numeric
);
I am using Hibernate with Spring Boot, PostgreSQL for the database and Thymeleaf to display the data in a web page. I managed to use Hibernate to pull the data from cars
and display it, all good, but now I want to join cars
with table thumbnails
on cars.thumbnail_id = thumbnails.id
and display the column image
from table thumbnails
instead of thumbnails_id
. This is what my thumbnails
table looks like:
CREATE TABLE public.thumbnails (
id integer NOT NULL,
image character varying(50)
);
And these are my entities:
// Car.java
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "cars")
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToOne
@JoinColumn(name = "id")
private Thumbnail thumbnail;
@Column(name = "engine_id")
private Integer engine_id;
@Column(name = "rating_id")
private Integer rating_id;
@Column(name = "speed")
private Integer speed;
@Column(name = "acc")
private Double acc;
@Column(name = "mass")
private Double mass;
}
// Thumbnail.java
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "thumbnails")
public class Thumbnail {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "image")
private String image;
}
What I don't know how to do is properly code that join
in. With my current code Hibernate matches the rows without considering the value of thumbnail_id
, it simply does "car_1 = thumbnail_1" even if "car_1" has "thumbnail_id" equal to 12, it still matches it to the first thumbnail and not to the 12th. Can anyone help me out?
Edit: Basically, what I'm trying to achieve through Hibernate is the following SQL query:
SELECT c.name, t.image, c.engine_id, c.rating_id, c.speed, c.acc, c.mass
FROM cars c
JOIN thumbnails t
ON c.thumbnails_id = t.id;