开发者

JPA query many to one association

开发者 https://www.devze.com 2022-12-26 04:38 出处:网络
I want to build the following pseudo query Select a From APDU a where a.group.id= :id group is a field in APDU class of the type APDUGroup.class.

I want to build the following pseudo query

Select a From APDU a where a.group.id= :id

group is a field in APDU class of the type APDUGroup.class.

I just want to get a list of APDUs based on APDUGroup's id.

How do i do that using a standard JPA query?

UPDATE

Yes, I have tried the above query and tried other variations for hours before posting in S/O. Here is the generated SQL for the query abov开发者_运维知识库e:

SELECT t1.ID, t1.status, t1.type, t1.modified, t1.response, t1.expectedSize, t1.created, t1.description, t1.sequence, t1.name, t1.command, t1.recurring, t1.auth, t1.createdBy, t1.APDUGroup, t1.modifiedBy FROM APDUGroup t0, APDU t1 WHERE ((t0.ID = ?) AND (t0.ID = t1.APDUGroup))

The query looks okay but nothing get selected from my table. There are at least 100 APDUs with APDUGroup = 1 in my test database.

I'm using eclipselink as the JPA provider.


Given the following Entities:

@Entity
public class APDU implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private APDUGroup group;

    //...

}

@Entity
public class APDUGroup implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    //...
}

The following query will return a list of APDUs for a given APDUGroup id:

select a from APDU a where a.group.id = :id

Oh, wait, that's your query :)


Entity 1:

@Entity
@Getter
@Setter
@Table(name = "invoices")
public class Invoice implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "invoice_id", updatable = false, nullable = false)
    private Long invoiceId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "person_id", referencedColumnName = "person_id", insertable = false, updatable = false, nullable = false)   
    private Person person;

    //...

}

Entity 2:

@Entity
@Getter
@Setter
@Table(name = "people")
public class Person implements Serializable {
    @Id
    @GeneratedValue
    @Column(name = "person_id", updatable = false, nullable = false)
    private Long personId;

    //...
}

Finally, Your Data Access Object (JPA Repository)

@Repository
public interface InvoiceRepository extends JpaRepository<Invoice, Long> {
    @Query(value="SELECT x FROM Invoice x WHERE x.person.personId = :myPersonId")
    List<Invoice> findInvoiceByPersonId (long myPersonId);
}

I hope this example has been helpful :)

0

精彩评论

暂无评论...
验证码 换一张
取 消