ajay
ajay

Reputation: 651

How to map two foreign keys mapping to the same primary key column in Hibernate (one-to-one)?

I am new to Java and Hibernate and I am trying to map the following scenario in Hibernate (using annotations).

I am dealing with the following two tables ( related to some ETL type of tasks).

Tasks
    |-TaskId
    |-SourceDatabase (FK to the Databases table)
    |-TargetDatabase (FK to the Databases table)

Databases
    |-DatabaseId (PK)
    |-TaskId (FK to the Tasks table)
    |-Other database details.

Each task has a sourceDatabase and a targetDatabase. Also each Database is related to only one Task. How can I map to this model in Hibernate using one-to-one mapping.

@Entity
public class Task implements Serializable
{
    @Id
    int taskId;

    //How to map  using one-to-one mapping??
    Database sourceDB;
    //how to map  using one-to-one mapping??
    Database targetDB;
}

@Entity
public class Database implements Serializable
{
    @Id
    int databaseId;

    //How to map using one-to-one mapping??
    Task task;  
}

I have removed all unnecessary code from the above code sample. Thanks in advance!!

Upvotes: 0

Views: 4540

Answers (2)

Nisarg Bhagavantanavar
Nisarg Bhagavantanavar

Reputation: 353

I was searching using mappedBy --for two foreign keys mapping to the same primary key column in Hibernate (one-to-one)?(for bidirectional relationship )

scenario with slight modification--as given below

Tasks
    |-TaskId
    |-SourceDatabase (FK to the Databases table)
    |-TargetDatabase (FK to the Databases table)

Databases
    |-DatabaseId (PK)
    |-Other database details.

I have took the code from @axtavt and modified for mappedBy so it will be helpful for others

  @Entity
   public class Task implements Serializable
   {
    ...
      @OneToOne @JoinColumn(name = "SourceDatabase")
      Database sourceDB;

      @OneToOne @JoinColumn(name = "TargetDatabase")
      Database targetDB;
   }

   @Entity
   public class Database implements Serializable
  {
     ...
       @OneToOne(cascade = {CascadeType.ALL},mappedBy = "sourceDB")
       Task taskSource; 

      @OneToOne(cascade = {CascadeType.ALL},mappedBy = "targetDB")
      Task taskTarget; 
   }

Upvotes: 0

axtavt
axtavt

Reputation: 242686

As far as I understand, you have 3 separate one-to-one relationships with their respective foreign keys, so you can map them as normal one-to-one relationships:

@Entity
public class Task implements Serializable
{
...
    @OneToOne @JoinColumn(name = "SourceDatabase")
    Database sourceDB;

    @OneToOne @JoinColumn(name = "TargetDatabase")
    Database targetDB;
}

@Entity
public class Database implements Serializable
{
     ...
     @OneToOne @JoinColumn(name = "TaskId")
    Task task;  
}

Upvotes: 3

Related Questions