开发者

Hibernate equivalent of ActiveRecord's has_many :through

In Rails it is possible to declare a transiti开发者_开发知识库ve relation as follows:

class Author < ActiveRecord::Base
    has_many :authorships
    has_many :books, :through => :authorships
end

Is it possible to do something similar in Hibernate? When I call author.getBooks() I want Hibernate to know to join authors with authorships with books.


I don't believe there is anything in Hibernate's mappings that can accomplish this, but you could simply add a getBooks() method to your Author class that calls the correct method on the authorships property:

public class Author {
    public Collection<Book> getBooks() {
        if (this.authorships != null) {
            return this.authorships.getBooks();
        }
        return null;    
    }
}

I'm not sure why the ORM would need to know about a transitive relationship between A and C between B, if you can just set that up in the class on it's own.


You can use a @ManyToMany with a @JoinTable to explain how the relationship has to be mapped.

@ManyToMany(targetEntity = Book.class)
@JoinTable(name = "authorships",
        joinColumns = {@JoinColumn(name = "author_id")},
        inverseJoinColumns = {@JoinColumn(name = "book_id")})        
public Set<Book> books;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜