What exactly does mappedby in hibernate mean?

邮差的信 提交于 2019-12-25 00:25:35

问题


I tried the documentation but I've got nothing. I tried searching for it on google and stackoverflow but there is still no help. I've got a singleton class and this class has a onetomany relationship to another class. Here's my code.

@Entity
public class HomeLibrary extends BaseModelObject {
    @OneToMany(mappedBy = "homeLibrary", cascade = { CascadeType.ALL })
    private Collection<Book> books = new ArrayList<Book>();

    private static HomeLibrary sharedHomeLibrary = new HomeLibrary();

    public static HomeLibrary getSharedHomeLibrary() {
        return sharedHomeLibrary;
    }

    public Collection<Book> getBooks() {
        return books;
    }

    public void setBooks(Collection<Book> books) {
        this.books = books;
    }

    private HomeLibrary() {
    }
}

And I got an error in testing. It seems that the table cannot be built.

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [HibernateApplicationContext-aop.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on edu.fudan.ss.persistence.hibernate.Book.homeLibrary references an unknown entity: edu.fudan.ss.persistence.hibernate.HomeLibrary

回答1:


Hibernate needs your default constructor to be present in order to create entity, since your constructor is hidden it cannot create your HomeEntity.

Either constructor should be public or package visibility, hibernate should be be able to use setAccessible(true) // Note I havent tried package visibility option.

Hibernate and in general framework who create entity uses Class<T>.newInstance() via reflection.

mappedBy means that mapping is done by the Owning side, the dependent need not define the mapping.

So in your case you will place mappedBy in Book if you are defining mapping in HomeLibraryor vice versa.

This post on SO speaks about creating objects via Factory method, you can use that to have your singleton object.



来源:https://stackoverflow.com/questions/10827027/what-exactly-does-mappedby-in-hibernate-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!