0

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.

maggalka
  • 1
  • 2

1 Answers1

0

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 from Driver to Car. To do that, you would need to have a @OneToMany mapping going from Driver to Car. (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?

Jeff Wang
  • 1,837
  • 1
  • 15
  • 29
  • Jeff, much thanks for answer. Yes? deriver in an Entity, you are right. i don't need info about matching car from drivers side, so there is only ManyToOne annotation. Also, here we imagine that we have only one car:) I understood that i was wrong thinking that @ManyToOne give us only id field, went through the code one more time and revealed, that there were function, that cut all info about driver except id 0_o, like this Driver getOnlyIdDriver(Driver driver){ Driver cuttedDriver = new Driver(); cuttedDriver.setId(driver.getId); return cuttedDriver; } – maggalka May 31 '18 at 07:15
  • Now i have another strange question. Could you tell me please, does hibernate make select query in Drivers table each time it get a car instance from the table? – maggalka May 31 '18 at 07:15
  • ManyToOne defaults to eager fetch, so yes, hibernate joins in the Driver for each car retrieved. see https://stackoverflow.com/questions/26601032/default-fetch-type-for-one-to-one-many-to-one-and-one-to-many-in-hibernate – Jeff Wang Jun 01 '18 at 16:16