-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Many to many mapping with composite keys
PostPosted: Thu Aug 18, 2011 8:52 am 
Newbie

Joined: Wed Mar 30, 2011 6:59 am
Posts: 3
This is a conceptional example, but I do not understand how to implement this.

I have tables as follows:

Code:
BOOK
------------
BOOK_ID

BOOK_AUTHOR
------------
BOOK_ID
AUTHOR_ID

AUTHOR
------------
AUTHOR_ID


Which map to the following hibernate many to many relationship:

Book

Code:
@Entity
public class Book implements Serializable {
@ManyToMany(
    targetEntity=org.hibernate.test.metadata.manytomany.Author.class,
    cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
@JoinTable(
    name="BOOK_AUTHOR",
    joinColumns=@JoinColumn(name="BOOK_ID"),
    inverseJoinColumns=@JoinColumn(name="AUTHOR_ID")
)
public Collection getAuthors() {
    return authors;
}

}               

Author

Code:
@Entity
public class Author implements Serializable {
@ManyToMany(
    cascade = {CascadeType.PERSIST, CascadeType.MERGE},
    mappedBy = "authors",
    targetEntity = Book.class
)
public Collection getBooks() {
    return books;
}

}

However, I live in a world where, a book and an author must have matching publishers but a book can exist without an author and an author can exist without a book. So, to my tables I have added a publisher id:

Code:
BOOK
------------
BOOK_ID
PUBLISHER_ID

BOOK_AUTHOR
------------
BOOK_ID
AUTHOR_ID
PUBLISHER_ID

AUTHOR
------------
AUTHOR_ID
PUBLISHER_ID


This in the database layer, would mean that the publisher id must match across all three tables meaning a book and author must have the same publisher, but how do I implement this using hibernate mapping? This is not a question on how to map things if I have an additional field such as description in the join table. It is how to map things so the publisher id can be forced to match across all three tables when creating a book_author relationship.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.