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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With