i'm new at JPA and need some advice. I have two tables, Car and Driver linked as ManyTyOne. And I would obtain Car entity with info about several drivers. Now i can get from Driver only driver_id, it looks like this, but need to receive also drivers name and lastName.
Class Car:
@Entity
public class Car {
@JsonIgnoreProperties({"telephone", "mail",})
@ManyToOne
@JoinColumn(name = "driver_id"),
private Driver driver;
...
}
@Entity
class Driver:
@JsonIgnoreProperties({"telephone", "mail",})
public class Driver {
private Long id;
private String firstName;
private String lastName;
private String telephone;
private String mail;
...
}
Table car SQL:
CREATE TABLE `car` (
`id` decimal(20) unsigned NOT NULL AUTO_INCREMENT,
`driver_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (driver_id) REFERENCES driver(id),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
At first I think that it's possible to receive also drivers name and surname the next way:
@JoinColumns({@JoinColumn(name = "driver_id"),
@JoinColumn(name = "first_name"),
@JoinColumn(name = "last_name")})
But documentation says, that @JoinColums is sutable only for composite fk. Please give me a hint, how can i do whats needed.
Assuming your
Driver
class is an entity (you didn't put in the @Entity annotation in the above code.)Your current mapping is saying that each driver can drive multiple cars. Since the many to one only exists on the
Car
side, there's no way to go fromDriver
toCar
. To do that, you would need to have a@OneToMany
mapping going fromDriver
toCar
. (Also, shouldn't this be a many to many mapping? each Driver can drive multiple cars. and each car can have multiple drivers?)In any case, given the mapping as above, you should be able to access driver.firstName and driver.lastName. What is the error when you are attempting to do that?