0

I have 2 entities in hibernate A and B. Here is the relevant code.

@Entity
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @OneToOne(mappedBy = "a", cascade = CascadeType.ALL)
    private B b;
}

@Entity
public class B {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    @Column(name = "a_id")
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name = "property", value = "a"))
    private Integer aId;

    @OneToOne(fetch = FetchType.LAZY, optional = false)
    @PrimaryKeyJoinColumn
    private A a;
}

I did the same as mentioned in the below mentioned link one to one mapping using primary key join column

However, when I do the following hql query,

"from A a left join a.b"

the join is taken on the following condition

a.id = b.id 

although what I desire is the following condition

a.id = b.aId
Mehdi Javan
  • 969
  • 6
  • 22
abhinav kumar
  • 113
  • 1
  • 7

2 Answers2

1

You must use @JoinColumn(name = "a_id") instead of @PrimaryKeyJoinColumn. By the way, you can't define two fields on the same column. However, if you need to do so you must make one of them not insertable and not updateable like this:

@JoinColumn(name = "a_id", insertable = false, updatable = false)
Mehdi Javan
  • 969
  • 6
  • 22
0

You have given the reference of class A to field a in class B.

@OneToOne(fetch = FetchType.LAZY, optional = false)
@PrimaryKeyJoinColumn
private A a;

And class B to field b in class A

@OneToOne(mappedBy="a", cascade=CascadeType.ALL)
    private B b;

so by default Hibernate create a join query with referenced field. So hibernate by default perform the join on a.id = b.id. But i think you can create your own query and use native query for performing join with a.id = b.aId.

CIPHER007
  • 366
  • 3
  • 12