Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

java - What exactly does mappedby in hibernate mean?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...