Search code examples
hibernatepojo

Hibernate POJO with two foreign keys from same table


How do I create a POJO WITH ANNOTATIONS so that hibernate will create the table below upon mapping? one column is followEE and one is followER.

CREATE TABLE friends(
  id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  followee_id INT(11) UNSIGNED NOT NULL,
  follower_id INT(11) UNSIGNED NOT NULL,
  start_time TIMESTAMP NOT NULL,
  end_time TIMESTAMP NOT NULL,
  PRIMARY KEY(id),
  KEY idx_fk_friends_followee_id (followee_id),
  KEY idx_fk_friends_follower_id (follower_id),
  CONSTRAINT `fk_friends_followee_id` FOREIGN KEY (followee_id) REFERENCES user (id) ON DELETE RESTRICT ON UPDATE CASCADE,
  CONSTRAINT `fk_friends_follower_id` FOREIGN KEY (follower_id) REFERENCES user (id) ON DELETE RESTRICT ON UPDATE CASCADE
)ENGINE=MyISAM DEFAULT CHARSET=utf8;

Solution

  • I am not sure what is your problem, as that is quite straight-forward I think:

    @Entity
    public class Friend {
      @Id
      private Long id;
    
      @ManyToOne
      private User follower;
    
      @ManyToOne
      private User followee;
    }