icyUser123
icyUser123

Reputation: 53

How to use hibernate to map three table together

below is my three table. I having problem mapping these three table together using @OneToMany.Not sure the right way to set up these three Entity. Thanks

Topic with many questions

Question with many answer options

CREATE TABLE `topic` (
  `topic_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(100) default null,
  PRIMARY KEY (`topic_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE `question` (
  `question_id` int unsigned NOT NULL AUTO_INCREMENT,
  `topic_id` int unsigned NOT NULL,
  `question` varchar(100) NOT NULL,
  `answer` varchar(100) NOT NULL,
  PRIMARY KEY (`question_id`),
  KEY `topic_id` (`topic_id`),
  CONSTRAINT `items_ibfk_1` FOREIGN KEY (`topic_id`) REFERENCES `topic` (`topic_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

CREATE TABLE `option` (
  `option_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `question_id` int(11) unsigned NOT NULL,
  `option` varchar(100) not null,
  PRIMARY KEY (`option_id`),
  KEY `question_id` (`question_id`),
  CONSTRAINT `items_ibfk_2` FOREIGN KEY (`question_id`) REFERENCES `question` (`question_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Upvotes: 0

Views: 81

Answers (1)

Sourav Sharma
Sourav Sharma

Reputation: 410

Below is the code snippet:
@Entity
class Topic
{
 //other fields
 @OneToMany(mappedBy="topic")
private List<Question> question;

}
@Entity
class Question
{
//other fields
@ManyToOne
@JoinColumn(name="topic_id")
private Topic topic;

@OneToMany(mappedBy="question")
private Option option;
}
@Entity    
class Option
{
//other fields
@ManyToOne
@JoinColumn(name="question_id")
private Question question;
}

Upvotes: 1

Related Questions