简体   繁体   中英

JPA Join Query using @Query in repository

I have two tables with composite primary keys and also it has foreign key relation ship. I am trying JPA mappings between these tables. We need to get the below join query result from JPA repository

select * from A i inner join B n on i.id = n.id where i.id = 'XXX' and i.version=99999;

Table: A fields are

id, name, version are primary keys

Table: B fields are

id, name, version, type are primary keys id, name, version, are foreign keys

@Table(name = "A")
@IdClass(APK.class)
public class A {

    @Id
    @Column(name = "ID")
    private String id;
    @Id
    @Column(name = "NAME")
    private String name;
    @Id
    @Column(name = "Version")
    private String version;

    //getter setter, toString, equals and hash code

    @OneToOne @JoinColumn(name="ID")
    private B b;
    getter setter

}

public class APK implements Serializable {

    private String id;
    private Long version;
    private String name;

    //getter setter, toString, equals and hash code

}

@Table(name = "B")
@IdClass(BPK.class)
public class B {

    @Id
    @Column(name = "ID")
    private String id;
    @Id
    @Column(name = "NAME")
    private String name;
    @Id
    @Column(name = "Version")
    private String version;
    @Id
    @Column(name = "TYPE")
    private Type type;

    // getter setter, toString, equals and hash code

    @OneToOne @MapsId("ID")
    private A a;

    //getter setter

}

public class APK implements Serializable {

    private String id;
    private Long version;
    private String name;
    private Type type;

    //getter setter, toString, equals and hash code

}

Getting the below error with this code:

Caused by: org.hibernate.AnnotationException: A Foreign key refering com.domain.data.B from com.domain.data.A has the wrong number of column. should be 5

Please Help on this.

The issue is resolved by using below mapping

@Table(name = "A")
@IdClass(APK.class)
public class A {



@OneToMany(fetch=FetchType.LAZY, mappedBy="a")
    private List<B> b; 
//getter and setter for b

}

@Table(name = "B")
@IdClass(BPK.class)
public class B {



@ManyToOne(fetch=FetchType.LAZY)
    @JoinColumns({
      @JoinColumn(name = "id", insertable = false, updatable = false),
      @JoinColumn(name = "name", insertable = false, updatable = false),
      @JoinColumn(name = "version", insertable = false, updatable = false)
    })
private A a;

//getter and setter for a

}

The JPQL query is "select i from B i INNER JOIN ia n WHERE n.id=:id"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM