Spring Roo, Hibernate, One to many relation creates additional table

*爱你&永不变心* 提交于 2019-12-03 05:57:20

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/5165743/spring-roo-hibernate-one-to-many-relation-creates-additional-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!