简体   繁体   中英

How to generate a single object from two tables in hibernate?

How to generate a single object from two tables in hibernate ?

I have two tables

  1. Question table
  2. options table
Question table
----------------
questionId | question 
--------------------
 1         | who invented java ?
 2         | who invented computer ?


 Options table
 --------------

 OptionId | option |questionId
 ------------------------------
  1       | santos | 1
  2       | james  | 1
  3       | jashuwa| 1
  4       | jhon   | 1
  5       | charles| 2
  6       | ram    | 2
  7       | raj    | 2
  8       | rohit  | 2

Now, I have a VO object like below

class QuestionAndOptions {

String questionId;
String question;
Sting option1Id;
String option1;
Sting option2Id;
String option2;
Sting option3Id;
String option3;
Sting option4Id;
String option4;

//getter and setter methods

}

Now, How can i create a QuestionAndOptions object using hibernate ?

Now, How can i create a list of QuestionAndOptions objects using hibernate ?

Any idea how i should this make ?

Based on provided tables graph I can see that relationship between Question table and Options table is one-to-many. So for your case objects will be following:

@Table(name="QUESTION")
public class Question{
    @Id
    @Column(...)
    private Long questionId;
    @Column(...)
    private String questionText;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "question")
    private List<Option> options
//getters and setters
}

@Table(name="OPTION")
public class Option{
    @Id
    @Column(...)
    private Long optionId;
    @Column(...)
    private String optionText;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "QUESTION_ID", nullable = false)
    private Question question;
    //getters and setters
}

From your table structure it looks like QuestionId is a foreign key in Options table and there is a one-to-many relationship between Question and options. Hibernate classes for this can be as follows -

class Option{
    String optionId;
    String option;
    Question question;
} 

class Question{
    String questionId;
    String question;
    Set<Option> options;
}

The QuestionAndOptions structure mentioned by you might be a little hard to maintain. You can obviously have some code to transform the hibernate objects retrieved into the structure you wish.

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