@OneToOne bidirectional mapping with @JoinColumn

Say I have a man

class Person{
    @Id Integer id;

    @OneToOne
    @JoinColumn(name = "person_id")
    Job myJob;
}

and job

class Job{
    @Id Integer id;
    Integer person_id;

    @OneToOne
    @PrimaryKeyJoinColumn(name = "person_id")
    Person currentWorker;
}

I can not compare the Person and Job with other entities during extraction.
What mistake am I making?

+3
source share
2 answers

Your code should be:

@Entity
public class Person implements Serializable {

    @Id Integer id;

    @OneToOne
    @JoinColumn(name = "id")
    Job myJob;
}

@Entity
public class Job implements Serializable {

    @Id Integer id;

    @OneToOne(mappedBy = "myJob")
    Person currentWorker;
}  

(pay a penalty for removing duplicate call "person_id" from Job)

or another approach to sharing a primary key:

@Entity
public class Person {
    @Id Integer id;

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    Job myJob;
}            

@Entity
public class Job {
    @Id Integer id;
} 
+7
source

, , "", hibernate.hbm2ddl.auto persistence.xml, Hibernate "--" . , ​​ . @JoinColumn @OneToOne (mappedBy) , Hibernate , FK . , , FK . Hibernate FK , FKg6wt3d1u6o13gdc1hj36ad1ot.

. , Contact (, , ..), OneToOne. , OneToOne , Hibernate , , FK . OneToOne , Hibernate NON-owning , . ( , .)

@Entity // common, non-owning entity
public class Contact implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)

private Integer id;

    @Column(name="fn")
    private String firstName;

    @Column(name="ln")
    private String lastName;

// "person" is the Contact entity as declared in Director
  @OneToOne(optional=false, mappedBy = "person")    
  private Director director;

 // GETTERS & SETTERS

@Entity // owning entity
public class Director implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", updatable = false, nullable = false)

private Integer id;

    @Column(name="title")
    private String title;

@OneToOne
    @JoinColumn
    private Contact person;

public Integer getId() {
        return id;
}   
public String getTitle() {
        return title;
}
public void setTitle(String title) {
        this.title = title;
}
public Contact getPerson() {
        return person;
}
public void setPerson(Contact person) {
        this.person = person;
}

, FK Director, :

alter table Director 
   add constraint FKg6wt3d1u6o13gdc1hj36ad1ot 
   foreign key (person_id) 
   references Contact (id)

FK Hibernate Director . , Contact (, ) + "_" + "id", person_id. , @OneToOne (mappedBy = "person" ) . , Hibernate FK , Director.

0

All Articles