简体   繁体   中英

Jpa unidirectional relation in the parent entity

I want to make unidirectional relation in the parent entity, Child entities have FK from the parent entity.

class Person {

    @Id
    @Column(name = "id")
    String id;


    @OneToOne
    @JoinColumn(name = "id", referencedColumnName = "person_id")
    Name name;
}

class Name {

    @Id
    @Column(name = "person_id")
    String personId;

    String name;
}

The Name table has FK from the person table. But I just want to define the relation in person entity only. I used @JoinColumn for mapping and set name as id from the person table

In the next example, I have one to many relations for example

class Parent {

    @Id
    @Column(name = "id")
    String id;

    @OneToMany
    @JoinColumn(name = "parent_id", referencedColumnName = "id")
    List<Child> childs;
    // fields...
}

class Child {

    @Id
    @Column(name = "Id")
    String id;


    @Column(name = "parent_id)
          String parentId;
}

In one to many relation in the @JoinColumn, I set name from the child table, and reference column from the Parent table. But when I defined the same unidirectional relation in the above person class with @OneToOne I have to set the @joincolumn name from the Person table and not from the Name table.

My question is why the defining name in these two join conditions are different, In one I have to set the name as the name of the PK column name from the same table, and in the second example, I have to set the name of the column from the child table.

The reason is that join column can be present only on ToOne side. As it's stated in the documentation :

public abstract java.lang.String name

(Optional) The name of the foreign key column. The table in which it is found depends upon the context.

  • If the join is for a OneToOne or ManyToOne mapping using a foreign key mapping strategy, the foreign key column is in the table of the source entity or embeddable.
  • If the join is for a unidirectional OneToMany mapping using a foreign key mapping strategy, the foreign key is in the table of the target entity.
  • If the join is for a ManyToMany mapping or for a OneToOne or bidirectional ManyToOne/OneToMany mapping using a join table, the foreign key is in a join table.
  • If the join is for an element collection, the foreign key is in a collection table.

Please note that the ability to use unidirectional @OneToMany with @JoinColumn was added only in JPA 2.0

@OneToMany
@JoinColumn(name = "parent_id")
List<Child> childs;

When you use unidirectional @OneToMany without @JoinColumn :

@OneToMany
List<Child> childs;

hibernate, for example, resorts to using a link table between the two joining entities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM