14

I'm new to spring mvc, roo and hibernate.

I'm trying to create two tables with 1:M relationship.

For example, I want two entities, Person and Car. One person can have many cars.

I've created entities using Roo

entity --class ~.domain.Person
field string Name
entity --class ~.domain.Car
field string Name
field reference --fieldName owner --type ~.domain.Person
field set --fieldName ownedCars --type ~.domain.Car --class ~.domain.Person --cardinality ONE_TO_MANY 

Generated class for car:

@RooJavaBean
@RooToString
@RooEntity
public class Car {

    private String Name;

    @ManyToOne
    private Person owner;
}

Generated class for Person

@RooJavaBean
@RooToString
@RooEntity
public class Person {

    private String Name;

    @OneToMany(cascade = CascadeType.ALL)
    private Set<Car> ownedCars = new HashSet<Car>();
}

However, in the database, there are 3 tables (insted of two)

Table CAR (as expected)

  CREATE TABLE "TEST"."CAR" 
   (    
    "ID" NUMBER(19,0), 
    "NAME" VARCHAR2(255 BYTE), 
    "VERSION" NUMBER(10,0), 
    "OWNER" NUMBER(19,0)
   )

Table PERSON (as expected)

  CREATE TABLE "TEST"."PERSON" 
   (
"ID" NUMBER(19,0), 
    "NAME" VARCHAR2(255 BYTE), 
    "VERSION" NUMBER(10,0)
   )

and also PERSON_OWNED_CARS (which is not expected, it's not many to many relationship)

  CREATE TABLE "TEST"."PERSON_OWNED_CARS" 
   (
"PERSON" NUMBER(19,0), 
    "OWNED_CARS" NUMBER(19,0)
   )

Why is the last table generated? What is the purpose of the last table, it's not many to many relationship? Can it be avoided? Am I doing something wrong?

Emir
  • 1,586
  • 3
  • 16
  • 32

1 Answers1

20

I'm not sure how Roo manages this, but you need to link sides of bidirectional relationships with mappedBy:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Set<Car> ownedCars = new HashSet<Car>();

Otherwise they are interpreted as two different unidirectional relationships, and relationship from Person to Car is implemented via join table (it's a default behaviour for unidirectional one-to-many relationships).

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • 5
    To do it from Roo itself the `--mappedBy owner`option can be used. Thanks for the question and the answer! – xverges Nov 30 '11 at 11:54
  • Greatly useful answer, I was really lost here about the table generation behaviour. – Guillaume Lebourgeois Feb 23 '12 at 11:01
  • What if `Car` is polymorphic and `Person` has_many `Cars` and `Company` has_many `Cars`, how do I handle this without additional table, since using @Any in `Car` will leave me with a uni-directional One-To-Many from `Entity` side thus creating a new table for each one-to-many relation. – krozaine Sep 18 '18 at 20:05