简体   繁体   中英

How to get key generated by Hibernate when I map a collection with @collectionId?

I am working on Quiz management. All mapping is done by Hibernate annotation for question to options. Question is an entity whereas all options are embedded object so I mapped option as follows :

QuestionMasterDTO's mapping for TabkidsMCQOptionMasterDTO :

    @ElementCollection(fetch=FetchType.EAGER,targetClass=TabkidsMCQOptionMasterDTO.class)
    @Fetch(FetchMode.SUBSELECT)
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    @CollectionTable(name="TABKIDS_MCQ_OPTION_MASTER",joinColumns={@JoinColumn(name="TMOM_QUESTION_ID")})
    @GenericGenerator(name="hilo-gen",strategy="hilo")
    @CollectionId(columns={@Column(name="TMOM_ID")},generator="hilo-gen", type=@Type(type="long"))
    public Collection<IOptionMaster> getOptions() {
        return options;
    }

Where TabkidsMCQOptionMasterDTO is :

   @Embeddable
    public class TabkidsMCQOptionMasterDTO  implements IOptionMaster {

        private String optionText;
        private boolean correct;


        @Column(name = "TMOM_OPTION_TEXT")
        public String getOptionText() {
            return optionText;
        }

        @Column(name = "TMOM_IS_CORRECT")
        public boolean isCorrect() {
            return correct;

        }
      //setters omitted
}

Now in above mapping you can see I am using a generator ie hilo-gen and assigning a unique id to every option available in collection and that column name is ' TMOM_ID '.

This line :

@GenericGenerator(name="hilo-gen",strategy="hilo")
@CollectionId(columns={@Column(name="TMOM_ID")},generator="hilo-gen", type=@Type(type="long"))

Now when I fetch a question from database by using Hibernate criteria I am getting all options associated with the question but not getting unique option id ie TMOM_ID . How to get this id ??

Hibernate mainly uses two type of mapping Entity Type and Value Type .

Entity type means It will have its own existence in the world ie It must have a primary key.

Whereas Value type don't have its own existence this means value type always dependent on Entity type.

As your problem I can see Option does not have its won existence because it must always dependent of Question which is an entity .

So from my point of view if you want to access Option Id, Option must also be an entity type this means You have to use @Entity on top of TabkidsMCQOptionMasterDTO rather than making it as @Embeddable .

So here you have to use @OneToMany in your question master and from Other side in TabkidsMCQOptionMasterDTO you have to use @ManyToOne mapping.

I hope this will help to achieve what you want to get.

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