JPA Mapping OneToOneToOne
I just started working with the Java Persistence API, and it became more convenient for me to use it. However, I came across a small design decision.
Let's say I run a car rental shop, multiple cars, multiple customers, and different customers can use different vehicles. To store the client's favorite cars, I would use the @OneToMany relationship from the client class and for the client currently renting a car, @OneToOne from the car class.
Now, how should I store the number of kilometers that the customer has driven with this vehicle? For example, with a MySQL database, I would create a table with three columns (four with an ID): customer_id, car_id, and kilometers. customer_id and car_id would be FK, and kilometers ... are self-explanatory.
What's the best approach to JPA? I could store, for example, from the customer class, an @OneToMany object as a list of a pair. The first would be the car, the second would be the number of kilometers the customer drove with that car. But this is not the case. Any suggestion?
source to share
You might have an object named RentalCarMileage, for example:
@Entity
public class RentalCarMileage implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private Car car;
@ManyToOne
private Customer customer;
@Column
private BigDecimal mileage;
}
@Entity
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "customer")
private List<RentalCarMileage> rentals;
}
@Entity
public class Car implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "car")
private List<RentalCarMileage> rentals;
}
This mapping assumes you want bi-directional communication, but @OneToMany is optional. You can simply run queries to get a rental car or customer.
source to share
I think you need an annotation @ManyToMany
. For example:.
@ManyToMany
@JoinTable( name="INTERMEDIATE_TABLE_NAME",
joinColumns = {@JoinColumn(name="customer_id_name")},
inverseJoinColumns = {@JoinColumn(name = "car_id_name")})
Set<Car> cars;
in class Customer
or vice versa in classCar
source to share