Hursant Bur Hursant Bur - 1 month ago 19
Java Question

Self OneToMany relation with jointable uknown column error

I have these

BaseNews
and
News
entity:

@MappedSuperclass
public class BaseNews extends Model {
public static Model.Finder<Long, News> find = new Model.Finder<Long, News>(News.class);

public static News getNewsById(Long newsId) {
return find.byId(newsId);
}

public static List<News> getNewsList(int pageIndex, int pageSize) {
return find.where()
.findPagedList(pageIndex, pageSize)
.getList();
}
}


@Entity
@Table(name = "news")
public class News extends BaseNews implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;


// @ManyToOne
// private News baseNews;


@OneToMany(cascade = CascadeType.ALL)//,mappedBy = "baseNews")
@JoinTable(name = "news_similar",
joinColumns = {@JoinColumn(name = "base_news_id")},
inverseJoinColumns = {@JoinColumn(name = "similar_news_id")}
)
private List<News> similarNews;

//getters, setters...
}


In both uni and bidirectional case

select t0.id c0, t0.base_news_id c1 from news t0


gives error Unknown column
base_news_id


Am I doing it wrong way?

Should I create new Entity NewsSimilar instead of using jointable?

Actually I am reversing existing table.

create table news_similar
(
id int auto_increment primary key,
base_news_id int not null,
similar_news_id int not null,
constraint news_similar_ibfk_1 foreign key (base_news_id) references news (id) on update cascade on delete cascade,
constraint news_similar_ibfk_2 foreign key (similar_news_id) references news (id) on update cascade on delete cascade
)


Edit: news_id was completely unrelated problem from other field, anyway solved it.

Answer Source

It turns out I have ManyToMany relation so, the solution is like this

@Entity
@Table(name = "news")
public class News extends BaseNews implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "news_similar",
               joinColumns = {@JoinColumn(name = "base_news_id")},
               inverseJoinColumns = {@JoinColumn(name = "similar_news_id")}
    )
    private List<News> similarNews;

   //getters, setters...
}

Came by this solution while reading this article:

https://www.thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/