dukable
dukable

Reputation: 4048

How to save an object in two different tables using Spring MVC and Hibernate

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?

Upvotes: 0

Views: 2083

Answers (2)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7302

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).

Upvotes: 0

ramirezag
ramirezag

Reputation: 564

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.

Upvotes: 1

Related Questions