0

Let's consider the following:

@Entity
@Table(name="person")
public class Person implements Serializable {

  @Id
  @GeneratedValue
  @Column(name="id")
  private int id;

  @Column(name="firstName")
  private String firstName;

  @Column(name="lastName")
  private String lastName;

  ...getters/setters...

}

and

@Entity
@Table(name="car")
public class Car implements Serializable {

  @Id
  @GeneratedValue
  @Column(name="id")
  private int id;

  @Column(name="brand")
  private String brand;

  @Column(name="model")
  private String model;

  @Column(name="personId")
  private String personId;

  ...getters/setters...

}

Let's imagine that a user is going to subscribe and enter his personal info, like first name, last name, the brand of his car, as well as the model of the car.

I do not want the personal info of the person to be stored in the same table than the car info.

I also would like to be able to retrieve the car information with the personId, this is why I have personId in the Car class.

Which annotations should I use to be able to accomplish this? Obviously I will need a constraint on the Car table and make personId a foreign key, right? What is the best way?

I have seen different things, what is the best?

2 Answers 2

1

In Car class, replace

@Column(name="personId")
private String personId;

with

@ManytoOne(fetch = FetchType.LAZY)
@CJoinColumn(name="person")
private Person person;

In Person class, add

@OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE})
private List<Car> cars;

You are now forming bi-directional one-to-many which means you can retrieve cars of person and person (ownder) of the car.

The cascade allows saving or updating of cars when person is saved. All cars are also deleted when person is removed.

Sign up to request clarification or add additional context in comments.

1 Comment

@dukable, for general requirement, this is the "best" answer.
0

It depends on your requirements. If you want to use the same vehicle for multiple users, then you shall make it an entity, and use a many-to-many relationship.

If you don't want to change your entity structure at all, but just the database mapping then look at @SecondaryTable and @SecondaryTables annotations, they define more tables for an entity, and then you shall specify which table to use for each column (otherwise they are assigned to main table).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.