I used schemaExport to create my tables like this
Configuration config = new Configuration();
config.addAnnotatedClass(Categories.class);
config.addAnnotatedClass(Article.class);
config.configure();
new SchemaExport(config).create(true, true);
The important pieces of Categories.java and Article.java are these:
Article.java
@Id
@GeneratedValue
public Long getId() {
return id;
}
@OneToMany( cascade = CascadeType.ALL )
public Set<Categories> getCategories() {
return categories;
}
Categories.java
@Id
@GeneratedValue
public Long getId() {
return id;
}
@ManyToOne(cascade = CascadeType.ALL)
public Article getArticleCategories() {
return articleCategories;
}
When run, Schema Export generates three tables: Article, Categories and article_categories. article_categories is an association table with two primary keys matching the keys from Article and Categories. Only Article and Categories have been added to the SessionFactory in my ApplicationContext.xml because I obviously don’t have the third table as a class since it was generated. I wrote this HQL:
"from Article a, article_categories ac, Categories c where ac.Article_id = a.id and ac.categories_id = c.id and c.category = 'p'"
Hibernate can’t run it because article_categories is not mapped. Do I need to map it? Is running native SQL instead of HQL a possible alternative, or should I avoid association tables all together? What’s the solution to this issue?
HQL doesn’t work with tables. It works with entities and their associations. Create joins between the entities in the HQL query, and Hibernate will generate the appropriate SQL, using the join tables, for you.
Example:
Read (at least) the HQL section of the reference manual.
Side note: the name of the entities should be singular: Category and not Categories. An article thus has a
Set<Category>, namedcategories. Much easier to read and understand that way. And thecategoryfield of Category should be namedname: it’s the name of the category, and not its category.