Search code examples
hibernatepostgresqlone-to-manyhibernate-annotations

Weird table name in Hibernate query over Postgresql database - "relation does not exist"


My problem started from this error: "relation "tag_article_tag" does not exist.

From Tag class:

@Entity
@Table(name = "tag")
public class Tag {
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<ArticleTag> articleTags;
...

From Article class:

@Entity
@Table(name = "article")
public class Article {
...
@OneToMany(mappedBy = "article", fetch = FetchType.EAGER, cascade =    CascadeType.ALL)
private Set<ArticleTag> articleTags;

My intermediary table / entity :

@Entity
@Table(name = "article_tag")
public class ArticleTag {
...
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "article_id")
private Article article;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "tag_id")
private Tag tag;

I've activate the show_sql property of Hibernate to do some debugging and at some point it was trying to select something from this table: "tag_article_tag". I've figure it out that it has something to do with the name from the Tag class ("tag") and the name of the set articleTags which has elements of type ArticleTag ( table name "article_tag" ). I've change the name from tag to tag1 and the error was than: "tag1_article_tag".

I know that the problem is somehow related to the set of objects but I don't know what exactly is. Any ideas ?


Solution

  • While I was posting this question I've found the problem :) .

    In the Article class I forgot about mappedBy field.

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<ArticleTag> articleTags;
    

    should include the mappedBy field:

    @OneToMany(**mappedBy="tag"**, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<ArticleTag> articleTags;