Search code examples
javaoraclehibernatehql

Fetching Data through Hibernate without passing Primary Key


I am using a composite primary key which is defined in Entity Class as :

@EmbeddedId
private ParticipantPrimaryKey pKey;

and the primary Key consists of Event Id and Student Id which are defined in PrimaryKey Entity Class.

Now i need to fetch the participants from the table which are participating in any particular Event.

The HQL query that is not working due to above problem:

select pe from ParticipantEntity pe where pe.eventId=?

If i use any other field then it'll work as they are present in the Entity Class but the Event ID is there in the primaryKey Entity.


Solution

  • You can use @ClassId, like:

     @ClassId(ParticipantPrimaryKey.class)
     class ParticipantEntity { ...
    

    Remove from the ParticipantEntity:

    @EmbeddedId
    private ParticipantPrimaryKey pKey;
    

    And also in the ParticipantEntity, add the two keys:

    @Id
    private Long eventId;
    
    @Id
    private Long studentId;
    

    After that, you can just:

    SELECT pe FROM ParticipantEntity pe where pe.eventId = :eventId