Illya Slobozhanin Illya Slobozhanin - 2 months ago 14
Java Question

Hibernate select error on inner join

I've got an error using hibernate/HQL

my tables are table1(id, data), where id -> primary key and table2(id, anotherdata), where id -> foreign key references to table1.id.

First class ->

@Entity
@Table(name = "table1")
public class Table1 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "data")
private String data;

@OneToOne
private Table2 table2;
//construct, get, set
}


Second class ->

@Entity
@Table(name = "table2")
public class Table2 {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "anotherdata")
private String data;
//get, set, construct
}


HQL query is SELECT t1.id, t1.data, t2.data FROM Table1 as t1 JOIN t1.table2 as t2

Hibernate log: select t1.id, t1.data, t2.anotherdata from table1 t1 inner join table2 on t1.t2_id = t2.id

this cause error ERROR: column t1.t2__id does not exist

in the end of this statement "on t1.t2_id = t2.id" i should have "on t1.id = t2.id" (pure sql)

How can i fix this? will be thankful for all your answers!

Answer

Your query is correct, but you should change the mapping:

@Entity
@Table(name = "table1")
public class Table1 {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "data")
    private String data;

    @OneToOne(mappedBy = "table1", cascade = CascadeType.ALL)
    private Table2 table2;
    //construct, get, set
}



@Entity
@Table(name = "table2")
public class Table2 {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "anotherdata")
    private String data;
    //get, set, construct

    @OneToOne
    @PrimaryKeyJoinColumn
    private Table1 table1;
}