Hibernate How to add a column in a middle table
Here's the details.
I have 2 entity tables with one to many relationship.
First, Exam
class has many Category
class. Hibernate generates this tables
______________
Exam
- Id
- Name
- Category
______________
Cat开发者_如何学Cegory
- Id
- Name
______________
Exam_Category
- Exam_Id
- Category_Id
I need to add an extra column in Exam_Category
table
ex:
______________
Exam_Category
- Exam_Id
- Category_Id
* User_Id
How am i going to accomplish this. if ever, how will i also get the user_id
value because the Exam_Category
is not exposed. Thanks
The best way to do this is to use a collection of elements.
@Entity
public class Exam {
@CollectionOfElements(fetch = FetchType.LAZY)
@JoinTable(name = "EXAM_CATEGORY", joinColumns = @JoinColumn(name = "FK_EXAM"))
public Set<CategoryEntry> getCategories() {
return this.categories;
}
}
@Embeddable
public class CategoryEntry{
private Category category;
private User user;
@ManyToOne
@JoinColumn(name = "FK_CATEGORY", nullable = false)
public Category getCategory() {
return this.category;
}
@ManyToOne
@JoinColumn(name = "FK_USER", nullable = false)
public User getUser() {
return this.user;
}
// ... setters and such
}
@Entity
public class Category {
}
This approach is cleaner than mapping it as an entity, since, logically, it is not an entity to begin with.
Then you can add some other methods in Exam
to get all the categories (without the users) or to retrieve it as a map, or whatever. You can completely hide this intermediate object through encapsulation, if that is required.
This is the case of many-to-many relationship with three tables (three foreign keys) involved. This cannot be achieved in Hibernate by simple mapping. You will have to extend your definition of Entity classes to support custom primary key column on the "middle" table·
Check out this reference.
You could use a Map field in your Exam class. See this post
精彩评论